views:

2212

answers:

3

I'm using SQL Server 2008. Say I create a temporary table like this one:
create table #MyTempTable (col1 int,col2 varchar(10))

How can I retrieve the list of fields dynamically? I would like to see something like this:

Fields:
col1
col2

I was thinking of querying sys.columns but it doesn't seem to store any info about temporary tables. Any ideas?

+1  A: 

The temporary tables are defined in "tempdb", and the table names are "mangled".

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%'

Marc

marc_s
I think this could cross scopes. If it's one time code, fine. If it's code that will have a real lifespan, problem.
jcollum
+3  A: 
select * from tempdb.sys.columns where object_id =
object_id('tempdb..#mytemptable');
kristof
It works fine on SQL Server 2008
Anthony
+1 - very simple and easy approach - I was too convoluted again ;-)
marc_s
Great, I will remove "tested only on SQLServer 2005" then
kristof
A: 
select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name like '#MyTempTable%'
Ed Guiness