user1141584 user1141584 - 1 month ago 12
SQL Question

How to get the row count for views from a database?

I'm trying to make a customized view that gets me the row count for all the views and tables of a database.

Getting the count of table is damn in SQL Server

SELECT TABLE_SCHEMA,
TABLE_NAME = TABLES.TABLE_NAME,
RECORD_COUNT = MAX(SYSINDEXES.ROWS)
FROM SYS.SYSINDEXES "SYSINDEXES",
INFORMATION_SCHEMA.TABLES "TABLES"
WHERE TABLES.TABLE_NAME = OBJECT_NAME(SYSINDEXES.ID)
AND TABLES.TABLE_TYPE = 'BASE TABLE'
GROUP BY TABLES.TABLE_SCHEMA,
TABLES.TABLE_NAME


Now, I need to get the rowcount for VIEWS

I feel the only way is to count the number of rows from the views
i.e.
count(*) from view_name


But, I could not find a way to have the rowcount for view along with view_name, table_schema and so on.

Any advance on this would be helpful.

Answer

Here , is the final solution:

SET NOCOUNT ON
DECLARE   @ViewName AS nVarChar(128)
    , @TmpQuery AS nVarChar(500)
    , @Out3 as int
DECLARE Cur_Views CURSOR FOR
SELECT schema_name(schema_id)+'.'+name as "Table_Name" FROM [sys].[all_views] 
OPEN Cur_Views
FETCH NEXT FROM Cur_Views INTO @ViewName
WHILE   @@Fetch_Status = 0 BEGIN
--SELECT  @Query = 'SELECT COUNT(*) AS [Count] FROM ' + @ViewName
--EXECUTE(@Query)
CREATE TABLE #Data (var int)
SELECT  @TmpQuery = 'SELECT COUNT(*) AS [Count] FROM ' + @ViewName
INSERT #Data exec (@TmpQuery)
SELECT @Out3 = var from #Data
--PRINT @ViewName
--PRINT @Out3
insert into Person.ViewCountTracker values(@ViewName,@Out3)
DROP TABLE #Data
FETCH NEXT FROM Cur_Views INTO @ViewName
END
CLOSE Cur_Views
DEALLOCATE Cur_Views
GO
--create table Person.ViewCountTracker
--(
--  ViewName varchar(255),
--  RowValue int
--)
--select * from Person.ViewCountTracker