How can I determine the space used by a table variable without using DATALENGTH on all columns?
eg:
DECLARE @T TABLE
(
a bigint,
b bigint,
c int,
d varchar(max)
)
insert into @T select 1,2,3, 'abc123'
exec sp_spaceused @T
Trying to work out how much memory a Table variable consumes when running a stored procedure.
I know in this example I can go:
SELECT DATALENGTH(a) + DATALENGTH(b) + DATALENGTH(c) + DATALENGTH(d)
But is there any other way other than doing DATALENGTH on all table columns?
The metadata for table variables is pretty much the same as for other types of tables so you can determine space used by looking in various system views in
tempdb.The main obstacle is that the table variable will be given an auto generated name such as
#3D7E1B63and I’m not sure if there is a straight forward way of determining itsobject_id.The code below uses the undocumented
%%physloc%%function (requires SQL Server 2008+) to determine a data page belonging to the table variable thenDBCC PAGEto get the associatedobject_id. It then executes code copied directly from thesp_spaceusedprocedure to return the results.Returns