好吧,没有简单的方法可以做到这一点。这是一个有点丑陋的代码,它可以满足您的需求。它基本上需要未知的输入查询,在 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