枚举transact sql列

时间:2010-11-17 16:12:26

标签: sql enumerate

有没有人知道如何使用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。 谢谢!

2 个答案:

答案 0 :(得分: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

...

答案 1 :(得分:3)

嗯,没有简单的方法可以做到这一点。这里有一些丑陋的代码,可以满足您的需求。它基本上采用未知的输入查询,在tempdb中创建表,枚举guid列并将它们转储到临时表#guids中。

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