0

有谁知道如何使用事务 sql 枚举事务 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 中特定记录的所有唯一标识符值写入#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 列并将它们转储到临时表 #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
于 2010-11-17T16:38:05.443 回答