Search code examples
sqlenumerate

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 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!


Solution

  • 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
    
    ...