9 jul 2012

do a search in each column of a database


the TSQL code works for me.
But i wonder if there is a more efficient way to do this.
use < DATABASENAME >
declare @ColumnName    varchar ( MAX )
declare @TableName    varchar ( MAX )
declare @GuidToSEarch    varchar ( MAX )


SET @GuidToSEarch = '96E897D-61C7-E911-ECBA-02EA4E855FBE'

declare c1 cursor
for
  -- START OF QUERY TO SEARCH ALL COLUMNS OF DB
SELECT
    SysObjects .[Name] as TableName,
    SysColumns .[Name] as ColumnName
    --SysTypes.[Name] As DataType,
    --SysColumns.[Length] As Length
FROM
   SysObjects INNER JOIN SysColumns
    ON SysObjects .[Id] = SysColumns . [Id]
    INNER JOIN SysTypes
    ON SysTypes .[xtype] = SysColumns . [xtype]
WHERE
    SysObjects .[type] = 'U' AND SysTypes .[Name] != 'sysname'
   and  SysTypes .[Name] = 'uniqueidentifier'
    group by    SysObjects. [Name] , SysColumns .[Name]
ORDER BY
   SysObjects. [Name] , SysColumns .[Name]
 -- END OF QUERY


  open c1
  fetch next from c1 into @TableName , @ColumnName

  while @@fetch_status = 0
  begin     
       exec ( 'SELECT * FROM ' + @TableName + ' where ' + @ColumnName + '=''' + @GuidToSEarch  + '''' )
       if (@@ROWCOUNT =1 )
       BEGIN

       print 'found in ' + @TableName
       -- close c1
        break ;
       END
       fetch next from c1 into @TableName, @ColumnName
  end

  close c1
  deallocate c1
  go