How can I get the actual data size per row in a SQL Server table?
Try this script:
declare @table nvarchar(128)
declare @idcol nvarchar(128)
declare @sql nvarchar(max)
--initialize those two values
set @table = 'YourTable'
set @idcol = 'some id to recognize the row'
set @sql = 'select ' + @idcol +' , (0'
select @sql = @sql + ' + isnull(datalength(' + name + '), 1)'
from sys.columns
where object_id = object_id(@table)
and is_computed = 0
set @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc'
PRINT @sql
exec (@sql)
The rows will be ordered by size, so you can check from top to down.
I liked the above from Jaime. I added some square brackets to handle weird column names.
declare @table nvarchar(128)
declare @idcol nvarchar(128)
declare @sql nvarchar(max)
--initialize those two values
set @table = 'YourTable'
set @idcol = 'some id to recognize the row'
set @sql = 'select ' + @idcol +' , (0'
select @sql = @sql + ' + isnull(datalength([' + name + ']), 1)'
from sys.columns where object_id = object_id(@table)
set @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc'
PRINT @sql
exec (@sql)
And I liked the above from Speedcat and extend it to list all Tables with rowcounts and total bytes.
declare @table nvarchar(128)
declare @sql nvarchar(max)
set @sql = ''
DECLARE tableCursor CURSOR FOR
SELECT name from sys.tables
open tableCursor
fetch next from tableCursor into @table
CREATE TABLE #TempTable( Tablename nvarchar(max), Bytes int, RowCnt int)
WHILE @@FETCH_STATUS = 0
begin
set @sql = 'insert into #TempTable (Tablename, Bytes, RowCnt) '
set @sql = @sql + 'select '''+@table+''' "Table", sum(t.rowsize) "Bytes", count(*) "RowCnt" from (select (0'
select @sql = @sql + ' + isnull(datalength([' + name + ']), 1) '
from sys.columns where object_id = object_id(@table)
set @sql = @sql + ') as rowsize from ' + @table + ' ) t '
exec (@sql)
FETCH NEXT FROM tableCursor INTO @table
end
PRINT @sql
CLOSE tableCursor
DEALLOCATE tableCursor
select * from #TempTable
select sum(bytes) "Sum" from #TempTable
DROP TABLE #TempTable