Wednesday, June 20, 2012

Calculate table width in SQL Server

1. use sp_help to get length for each column, paste them to spreadsheet to have a quick summary
2. use dbcc showcontig() with tableresults to get the statistics such as min record size, max record size and average record size
3. in new version of SQL server(2005 and above), use DMV to query the statistics information

sys.dm_db_index_physical_stats ( 
    { database_id | NULL | 0 | DEFAULT }
  , { object_id | NULL | 0 | DEFAULT }
  , { index_id | NULL | 0 | -1 | DEFAULT }
  , { partition_number | NULL | 0 | DEFAULT }
  , { mode | NULL | DEFAULT }
)

SELECT CAST(DB_NAME(DATABASE_ID) AS VARCHAR(20)) AS 'DatabaseName',
CAST(OBJECT_NAME([OBJECT_ID]) AS VARCHAR(20)) AS 'TableName',
index_id, 
index_type_desc,
alloc_unit_type_desc,
min_record_size_in_bytes, 
max_record_size_in_bytes, 
avg_record_size_in_bytes 
FROM SYS.DM_DB_INDEX_PHYSICAL_STATS (DB_ID('db'),NULL,NULL,NULL,'DETAILED')
ORDER BY avg_record_size_in_bytes DESC;

No comments: