September 22, 2014 at 6:12 am
Hi i want count of rows. below query return null value(@count) please tell me how can i get count of rows here i pass table name as parameter to store procedure.
create proc usp_get_counts
(
@tablename varchar(50)
)
as
begin
declare @query Nvarchar(100),@count int
set @query=N'select '+cast(@count as nvarchar(1))+'=count(*) from '+@tablename
EXECUTE(@query)
SELECT @count
end
--chalam
September 22, 2014 at 6:31 am
CREATE PROC usp_get_counts (@tablename VARCHAR(50))
AS
BEGIN
SELECT SUM(row_count) AS RowCount
FROM sys.dm_db_partition_stats AS ddps
WHERE ddps.index_id IN (0,1) AND ddps.object_id = OBJECT_ID(@tablename)
END
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
September 22, 2014 at 6:34 am
...or what Gail posted! 😉
September 22, 2014 at 8:16 am
Note DM view do not take care of transactions. SELECT COUNT(*) and DM may return different number of rows.
September 22, 2014 at 8:22 am
The DMV should be transactionally consistent. This isn't the sysindexes from SQL 2000 era which could be and was wrong at times.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
September 23, 2014 at 12:32 am
For example, above DVM will count rows inserted by uncommited transactions. SQL Server 2008.
Open two queries in Managment Studio. In first query run
CREATE TABLE [testDVM](
[a] [int] NULL
) ON [PRIMARY]
GO
BEGIN TRAN;
INSERT testDVM
SELECT top(10) 1
FROM sys.all_objects;
Start the second query
DECLARE @RowCount1 INT;
SELECT @RowCount1=SUM(row_count)
FROM sys.dm_db_partition_stats AS ddps
WHERE ddps.index_id IN (0,1) AND ddps.object_id = OBJECT_ID('TestDVM');
SELECT Count(*) - @RowCount1 AS delta
FROM TestDVM;
return to the first one and run
INSERT testDVM
SELECT top(20) 2
FROM sys.all_objects;
COMMIT TRAN;
See the result of the second query. Apparently DVM was not waiting for the transaction to commit.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply