输出一个数据库中所有表的数据量

此TSQL语句是针对SQL Server 2012编写。如果使用之前版本,需要对部分语句进行重写。

 1 USE [数据库名称];

 2 

 3 --1.建立临时表,来存放结果。

 4 /*

 5 临时表数据结构:

 6 struct Table_TableCount

 7 {

 8     string TableName;//表名字

 9     Int64 Count;//表数据量

10 }

11 */

12 --1.1 如果临时表存在,则删除

13 If Exists ( Select * From Tempdb..SysObjects Where ID = Object_id( 'TempDB..#Table_TableCount') )

14     Begin

15         Drop Table #Table_TableCount;

16     End;

17 

18 --1.2 建立临时表

19 create table #Table_TableCount

20 (

21     [TableName] [Nvarchar](max) NOT NULL,

22     [Count] [Bigint] NOT NULL

23 );

24 

25 --2.用游标Cursor_Table,遍历所有表

26 DECLARE Cursor_Table CURSOR FOR

27     SELECT name from sysobjects WHERE xtype = 'u' AND name <> 'dtproperties';

28 OPEN Cursor_Table;

29 DECLARE @tableName NVARCHAR(MAX);

30 FETCH NEXT from Cursor_Table INTO @tableName;

31 WHILE @@fetch_status = 0

32 BEGIN

33     --3.获取游标所指向的当前表的名称,以及数据量,将这两个信息插入临时表

34     DECLARE @tempSQLText NVARCHAR(MAX) = 'DECLARE @CurrentTableCount Bigint = ( SELECT COUNT(*) From [' + @tableName + '] ); INSERT INTO #Table_TableCount ([TableName],[Count]) VALUES (''' + @tableName + ''', @CurrentTableCount );';

35     EXEC( @tempSQLText );

36     FETCH NEXT from Cursor_Table INTO @tableName;

37 END

38 CLOSE Cursor_Table;

39 DEALLOCATE Cursor_Table;

40 

41 --4.输出(通过构造不同的SELECT语句,来获取不同的输出方式)

42 SELECT * FROM #Table_TableCount WHERE [COUNT] > 0 ORDER BY [Count] DESC; --当前是输出数据量大于0,并且按数据量的降序排序

 

你可能感兴趣的:(数据库)