How to get field names from a temporary table (SQL Server 2008)

I am using SQL Server 2008. Let's say I am creating a temporary table like this:

create table #MyTempTable (col1 int,col2 varchar(10)) 

How can I get a list of fields dynamically? I would like to see something like this:

 Fields: col1 col2 

I thought about the sys.columns query, but it does not seem to store information about temporary tables. Any ideas?

+55
sql sql-server sql-server-2008 temp-tables
Apr 16 '09 at 13:22
source share
7 answers
 select * from tempdb.sys.columns where object_id = object_id('tempdb..#mytemptable'); 
+105
Apr 16 '09 at 13:27
source share
— -
 select * from tempdb.INFORMATION_SCHEMA.COLUMNS where table_name like '#MyTempTable%' 
+24
Apr 16 '09 at 13:27
source share

Temporary tables are defined in tempdb, and table names are crippled.

This query should do the trick:

 select c.* from tempdb.sys.columns c inner join tempdb.sys.tables t ON c.object_id = t.object_id where t.name like '#MyTempTable%' 

Mark

+6
Apr 16 '09 at 13:26
source share

Use information_schema and not encounter other sessions:

 select * from tempdb.INFORMATION_SCHEMA.COLUMNS where table_name = object_name( object_id('tempdb..#test'), (select database_id from sys.databases where name = 'tempdb')) 
+5
Jun 13 '13 at 22:17
source share

you can do it by following also ..

 create table #test (a int, b char(1)) select * From #test exec tempdb..sp_columns '#test' 
+3
Apr 24 '13 at 5:55
source share

Anthony

try the following. this will give the expected ur output

 select c.name as Fields from tempdb.sys.columns c inner join tempdb.sys.tables t ON c.object_id = t.object_id where t.name like '#MyTempTable%' 
+1
Nov 27
source share
 select * from tempdb.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=OBJECT_NAME(OBJECT_ID('#table')) 
0
09 Oct '17 at 13:50
source share



All Articles