SQL Server 2008 を使用しています。次のような一時テーブルを作成するとします。
create table #MyTempTable (col1 int,col2 varchar(10))
フィールドのリストを動的に取得するにはどうすればよいですか? 私はこのようなものを見たいです:
Fields:
col1
col2
sys.columns のクエリを考えていましたが、一時テーブルに関する情報が保存されていないようです。何か案は?
SQL Server 2008 を使用しています。次のような一時テーブルを作成するとします。
create table #MyTempTable (col1 int,col2 varchar(10))
フィールドのリストを動的に取得するにはどうすればよいですか? 私はこのようなものを見たいです:
Fields:
col1
col2
sys.columns のクエリを考えていましたが、一時テーブルに関する情報が保存されていないようです。何か案は?
select * from tempdb.sys.columns where object_id =
object_id('tempdb..#mytemptable');
select *
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name like '#MyTempTable%'
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'))
一時テーブルは「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%'
マルク
あなたも次の方法でそれを行うことができます..
create table #test (a int, b char(1))
select * From #test
exec tempdb..sp_columns '#test'
アンソニー
以下のものを試してください。期待される出力が得られます
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%'