How to write a cursor for Row Count

Hi Folks,

I have a table which table has :Identity Column (Identity), Schema name and Table_Name.

So I would like to write a cursor For each Table Count(*) from Table--@Cnt Int , Schemaname and Tablename need to store another table.

 Implement a USP, using a cursor that scan the  table, generate select count statement from configuration table  and fire the select count statement and record the result of the query in the log table :

Can you please help me how can I write a cursor and Import Those results into to Another table. Can you please help me.

Thanks in Advance.






May 20th, 2015 6:16am

Try this 

CREATE TABLE #RowcountofAllTable
(
    TableName varchar(255),
    TotalRowCount INT
)

EXEC sp_MSForEachTable @command1='INSERT #RowcountofAllTable (TableName, TotalRowCount) SELECT ''?'', COUNT(*) FROM ?'
SELECT TableName, TotalRowCount FROM #RowcountofAllTable ORDER BY TableName, TotalRowCount DESC


-- Drop temp table
IF OBJECT_ID('tempdb..#RowcountofAllTable') IS NOT NULL
BEGIN
	DROP TABLE #RowcountofAllTable;
END

Free Windows Admin Tool Kit Click here and download it now
May 20th, 2015 6:38am

Hi Cherukuri19,

You don't have to loop each table to get the row count. To get the row count, you can reference below sample.

CREATE TABLE YourTable (SchemaName SYSNAME,TableName SYSNAME)
 
SELECT
      QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName]
      , SUM(sdmvPTNS.row_count) AS [RowCount]
FROM
      sys.objects AS sOBJ
      INNER JOIN sys.dm_db_partition_stats AS sdmvPTNS
            ON sOBJ.object_id = sdmvPTNS.object_id
      INNER JOIN YourTable YT
			ON SCHEMA_NAME(sOBJ.schema_id)= YT.SchemaName AND sOBJ.name=YT.TableName
WHERE 
      sOBJ.type = 'U'
      AND sOBJ.is_ms_shipped = 0x0
      AND sdmvPTNS.index_id < 2
GROUP BY
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [TableName]
GO

See more approaches from the below link.
SQL Server Row Count for all Tables in a Database

If you have any question, feel free to let me know.

May 21st, 2015 2:28am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics