SQLServer遍历数据库所有表及统计表数据总数
时间:2010-09-05 来源:hijarry
SQLServer遍历数据库所有表及统计表数据总数:
代码
1 DECLARE @TableName varchar(255);
2 CREATE TABLE #GetRecordingTempTable([id] [INT] IDENTITY(1,1) NOT NULL, [TableName] varchar(255) NOT NULL, [RecordingCount] INT);
3 DECLARE Table_Cursor CURSOR FOR SELECT [name] FROM sysobjects WHERE xtype='U';
4 OPEN Table_Cursor;
5 FETCH NEXT FROM Table_Cursor INTO @TableName;
6 WHILE(@@FETCH_STATUS=0)
7 BEGIN
8 EXEC('INSERT INTO #GetRecordingTempTable ([TableName],[RecordingCount]) SELECT '''+@TableName+''', COUNT(0) FROM ['+@TableName+'];');
9 FETCH NEXT FROM Table_Cursor INTO @TableName;
10 END
11 CLOSE Table_Cursor;
12 DEALLOCATE Table_Cursor;
13 SELECT [TableName] AS [表名称],[RecordingCount] AS [总记录数] FROM #GetRecordingTempTable ORDER BY [RecordingCount] DESC;
14 DROP TABLE #GetRecordingTempTable;
15 GO
2 CREATE TABLE #GetRecordingTempTable([id] [INT] IDENTITY(1,1) NOT NULL, [TableName] varchar(255) NOT NULL, [RecordingCount] INT);
3 DECLARE Table_Cursor CURSOR FOR SELECT [name] FROM sysobjects WHERE xtype='U';
4 OPEN Table_Cursor;
5 FETCH NEXT FROM Table_Cursor INTO @TableName;
6 WHILE(@@FETCH_STATUS=0)
7 BEGIN
8 EXEC('INSERT INTO #GetRecordingTempTable ([TableName],[RecordingCount]) SELECT '''+@TableName+''', COUNT(0) FROM ['+@TableName+'];');
9 FETCH NEXT FROM Table_Cursor INTO @TableName;
10 END
11 CLOSE Table_Cursor;
12 DEALLOCATE Table_Cursor;
13 SELECT [TableName] AS [表名称],[RecordingCount] AS [总记录数] FROM #GetRecordingTempTable ORDER BY [RecordingCount] DESC;
14 DROP TABLE #GetRecordingTempTable;
15 GO
相关阅读 更多 +