73

SQL Server 2008 を使用しています。次のような一時テーブルを作成するとします。

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

フィールドのリストを動的に取得するにはどうすればよいですか? 私はこのようなものを見たいです:

Fields:
col1
col2

sys.columns のクエリを考えていましたが、一時テーブルに関する情報が保存されていないようです。何か案は?

4

7 に答える 7

137
select * from tempdb.sys.columns where object_id =
object_id('tempdb..#mytemptable');
于 2009-04-16T13:27:18.510 に答える
30
select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name like '#MyTempTable%'
于 2009-04-16T13:27:19.417 に答える
8

information_schema を使用し、他のセッションと衝突しないようにするには:

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name =
    object_name(
        object_id('tempdb..#test'),
        (select database_id from sys.databases where name = 'tempdb'))
于 2013-06-13T22:17:26.903 に答える
7

一時テーブルは「tempdb」で定義され、テーブル名は「マングル」されています。

このクエリはうまくいくはずです:

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

マルク

于 2009-04-16T13:26:07.267 に答える
3

あなたも次の方法でそれを行うことができます..

create table #test (a int, b char(1))

select * From #test

exec tempdb..sp_columns '#test'
于 2013-04-24T05:55:55.450 に答える
1

アンソニー

以下のものを試してください。期待される出力が得られます

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%'
于 2012-11-27T13:54:35.083 に答える