我正在尝试创建一个自定义的视图,该视图可以让我获得数据库所有视图和表的行数。
在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
现在,我需要获取VIEWS的行数
我觉得唯一的方法是从视图中计算行数,即 count(*) from view_name
count(*) from view_name
但是,我找不到一种方法来让视图的行数以及view_name,table_schema等。
在这方面的任何进步将是有帮助的。
这是最终的解决方案:
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