Enumerate transact sql columns
Does anyone know how to use transact sql to enumerate the column types within a transact sql result set. I want to do something like this (pseudo-code):
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
But 开发者_C百科I need to do it from within transact sql, and I don't know in advance what the structure of table1 will be. Anyone know how? I'm using MS SQL 2005. In a nutshell I want all uniqueidentifier values for a specific record in table1 to be written to #table2. Thanks!
Warning, not tested:
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
...
Well, there is no easy way to do this. Here is a bit ugly code, that does what you need. It basically takes unknown input query, creates table in tempdb, enumerates guid columns and dumps them into temp table #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
精彩评论