I am a beginner to SQL Server Database. I have a basic question.
How to retrieve the column names of a temporary table
in SQL Server
?
I have tried querying the sys.objects
, but the table is not listing there.
I am a beginner to SQL Server Database. I have a basic question.
How to retrieve the column names of a temporary table
in SQL Server
?
I have tried querying the sys.objects
, but the table is not listing there.
Temp tables are stored in the tempdb
database so you have to query the views from the tempdb
database. Something like this:
SELECT c.name
FROM tempdb.sys.objects o
INNER JOIN tempdb.sys.columns c ON c.object_id = o.object_id
WHERE o.name LIKE '#TempTableName%';
SELECT Obj.NAME
,Col.NAME
FROM tempdb.sys.objects Obj
INNER JOIN tempdb.sys.columns Col ON Obj.object_id = Col.object_id
WHERE Obj.NAME LIKE '#tmp%'
But please note that the local temporary table names will not be unique. We can have the same names from different sessions. So be careful with the query.
Here's how to get the temp table for just the current session.
SELECT c.name
FROM tempdb.sys.objects o
INNER JOIN tempdb.sys.columns c ON c.object_id = o.object_id
WHERE o.object_id = object_id('tempdb..#TempTableName)
`SELECT STUFF(
`(SELECT ',' + LTRIM(RTRIM(ISNULL(name,'')))
`FROM tempdb.sys.columns
`WHERE Object_ID = Object_ID(N'tempdb..#TEMP')
`FOR XML PATH(''), TYPE).value('.','varchar(max)'), 1, 1, '')
`AS comma_separated_list