I can declare a table variable as such:
DECLARE @tv_source TABLE(c1 int,
providerName varchar(50),
providerSMS varchar(50))
If I then execute the following, I see the table name similar to: "#468862B0"
select top 1 * from tempdb.sys.tables where type = 'U' order by create_date desc
select TOP 1 name,* from tempdb.sys.sysobjects ORDER BY CRDATE desc
If I then immediately execute:
select TOP 3 *
from tempdb.sys.columns
where object_id in (select TOP 1 object_id from tempdb.sys.tables ORDER BY Create_date desc)
I see the columns I declared above for the table variable.
My question is, is there any way to definitively associate those columns with the name I declared in the table declaration above "@tv_source"?
In a normal table, you would see the actual name but, as noted above, table variables get morphed into a hex value (which, btw is the hex value of the object_id).
You can query your table variable
top(0)
with anouter apply
from one row usingfor xml path('')
and then query the XML for the element names.This will work as long as your column names does not have names that is invalid XML element names. The column names can for instance not use ampersand or space.
Another option would be to use the
xmlschema
directive offor xml auto
. This solution does handle invalid XML characters but they are escaped so if you have a column name with a space like[provider Name]
the result will beprovider_x0020_Name
.You need to store the resulting XML to a variable and query that for the information you want.
The XML created by
xmlschema
contains more information that might be of interest. You can retrieve the table variable name and the datatypes as well.I see from your comments that this exercise is for learning so you don't have a specific use case or need. That said, another way to get detailed column meta-data from a table variable variable is with sp_describe_first_result_set.