andrew4582

View Table Sizes TSQL

Dec 27th, 2010
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.90 KB | None | 0 0
  1. --DROP TABLE #table_sizes
  2.  
  3. CREATE TABLE #table_sizes(
  4.     [schema_name] [nvarchar](50),
  5.     [table_name] [nvarchar](255),
  6.     [size_mb] [decimal](18, 2),
  7.     [row_count] [int])
  8.  
  9.  
  10. DECLARE tables_cursor CURSOR
  11.     FOR
  12.         select TOP 100 percent
  13.             t.object_id,t.name as schema_name,t.TableName,t.TableSize
  14.         from
  15.             (select
  16.                   sys.objects.object_id,
  17.                   sys.schemas.name,
  18.                   sys.objects.name as TableName,
  19.                   sum(reserved_page_count) * 8.0 / 1024 as TableSize,
  20.                   sys.objects.type
  21.             from sys.objects inner join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id
  22.                   ,sys.dm_db_partition_stats
  23.             where
  24.                   sys.dm_db_partition_stats.object_id = sys.objects.object_id
  25.             group by sys.objects.object_id,sys.schemas.name,sys.objects.name,sys.objects.type) t
  26.  
  27.         WHERE t.type = 'u'
  28.         ORDER BY t.TableSize desc
  29.        
  30.     OPEN tables_cursor;
  31.    
  32.     DECLARE @sys_id int;
  33.     DECLARE @tablename sysname;
  34.     DECLARE @schema_id varchar(20);
  35.     DECLARE @tablesize decimal(18, 2);
  36.     DECLARE @tablesize_desc varchar(20);
  37.  
  38.     FETCH NEXT FROM tables_cursor INTO @sys_id,@schema_id,@tablename,@tablesize;
  39.     WHILE (@@FETCH_STATUS <> -1)
  40.     BEGIN;
  41.        
  42.         DECLARE @Command nvarchar(1000);
  43.         DECLARE @ParmDefinition nvarchar(500);
  44.         DECLARE @Result int;
  45.        
  46.         SET @Command = N'SELECT @RCOUNTOUT = COUNT(*) FROM [' + @schema_id + '].[' + @tablename + ']';
  47.         SET @ParmDefinition = N'@RCOUNTOUT int OUTPUT';
  48.        
  49.         EXECUTE sp_executesql
  50.             @Command
  51.             ,@ParmDefinition
  52.             ,@RCOUNTOUT = @Result OUTPUT;
  53.            
  54.         INSERT INTO #table_sizes
  55.             ([schema_name]
  56.            ,[table_name]
  57.            ,[size_mb]
  58.            ,[row_count])
  59.         VALUES
  60.             (@schema_id,
  61.             @tablename,
  62.             @tablesize,
  63.             @Result)
  64.        
  65.        FETCH NEXT FROM tables_cursor INTO @sys_id,@schema_id,@tablename,@tablesize;
  66.    
  67.     END;
  68.    
  69.     CLOSE tables_cursor;
  70.     DEALLOCATE tables_cursor
  71.    
  72.  
  73. SELECT * FROM #table_sizes
  74. ORDER BY #table_sizes.row_count desc
  75.  
  76. DROP TABLE #table_sizes
Advertisement
Add Comment
Please, Sign In to add comment