0

Transact sql を使用して、transact sql の結果セット内の列の型を列挙する方法を知っている人はいますか。私はこのようなことをしたい(疑似コード):

for each column in (select * from table1 where id=uniquekey)
{
if (column.type=uniqueidentifier){
insert into #table2(id) values (column.value)
}}
then do some stuff with #table2

しかし、transact sql 内から実行する必要があり、table1 の構造がどうなるかを事前に知りません。誰でも方法を知っていますか?私は MS SQL 2005 を使用しています。簡単に言えば、table1 の特定のレコードのすべての uniqueidentifier 値を #table2 に書き込む必要があります。ありがとう!

4

2 に答える 2

3

警告、未テスト:

Create Table #Cols(ColName SysName)
Declare @More Bit
Declare CCol Cursor Local Fast_Forward For Select Column_Name From Information_Schema.Columns Where Table_Name = 'Table1' And Data_Type = 'UniqueIdentifier'
Declare @CCol SysName
Declare @SQL National Character Varying(4000)

Set @More = 1
Open CCol

While (@More = 1)
Begin
  Fetch Next From CCol Into @CCol
  If (@@Fetch_Status != 0)
    Set @More = 0
  Else
  Begin
    Set @SQL = N'Insert Into #Table2(ID) Select [' + @CCol + N'] From Table1'
    Execute (@SQL)
  End
End

Close CCol
Deallocate CCol

...
于 2010-11-17T16:33:39.833 に答える
3

まあ、これを行う簡単な方法はありません。これは、必要なことを行う少し醜いコードです。基本的に、不明な入力クエリを受け取り、tempdb にテーブルを作成し、guid 列を列挙して一時テーブル #guid にダンプします。

declare @sourceQuery varchar(max)
set @sourceQuery = 'select 1 as IntCol, newid() as GuidCol1, newid() as GuidCol2, newid() as GuidCol3' 
declare @table varchar(255) = replace( cast( newid() as varchar(40)), '-', '' )


print @table
declare @script varchar(max)
set @script = '
select *
into tempdb..[' + @table + ']
from ( ' + @sourceQuery + ' ) as x
'
exec( @script )


create table #guids
(
    G uniqueidentifier not null
)

declare cr cursor fast_forward read_only for
select c.name
from tempdb.sys.objects as s
inner join tempdb.sys.columns as c
    on s.object_id = c.object_id
where s.name = @table
    and c.system_type_id = 36 -- guid

declare @colName varchar(256)

open cr
fetch next from cr into @colName
while @@FETCH_STATUS = 0
begin
    set @script = ' 
    insert into #guids(G)
    select ' + @colName + ' from (' + @sourceQuery + ') as x '

    exec( @script )

    fetch next from cr into @colName
end

close cr
deallocate cr

select * from #guids

exec( 'drop table tempdb..[' + @table + ']' )
drop table #guids
于 2010-11-17T16:38:05.443 に答える