Thursday, April 22, 2010

SQL Query to Search All Tables for an INT

Here is a really good query I want to remember for searching all tables in a database for a specific integer.
declare  @sql varchar(8000), @tbl varchar(255), @col varchar(255), @data  varchar(50)

set @data = '249753'

declare cur_tbl cursor for
select a.name, b.name from sysobjects a, syscolumns b, systypes c where a.id = b.id and a.type = 'U' and c.xtype = b.xtype and c.name in ( 'int' )
open cur_tbl
fetch next from cur_tbl into @tbl, @col
while @@fetch_status = 0
begin
set @sql = '
if exists (select * from [' + @tbl + '] where convert( varchar(255), [' + @col + '] ) = ''' + @data + ''')
select tbl=''' + @tbl + ''', col=''' + @col + ''', [' + @col + '], * from [' + @tbl + '] where convert( varchar(255), [' + @col + '] ) = ''' + @data + '''
'
exec(@sql)

fetch next from cur_tbl into @tbl, @col
end
close cur_tbl
deallocate cur_tbl


Or to search for a string
declare  @sql varchar(8000), @tbl varchar(255), @col varchar(255), @data  varchar(50)

set @data = 'string you are looking for'

declare cur_tbl cursor for
select a.name, b.name from sysobjects a, syscolumns b, systypes c where a.id = b.id and a.type = 'U' and c.xtype = b.xtype and c.name in ( 'varchar', 'nvarchar', 'text', 'ntext' )
open cur_tbl
fetch next from cur_tbl into @tbl, @col
while @@fetch_status = 0
begin
set @sql = '
if exists (select * from [' + @tbl + '] where convert( varchar(255), [' + @col + '] ) like ''%' + @data + '%'')
select tbl=''' + @tbl + ''', col=''' + @col + ''', [' + @col + '], * from [' + @tbl + '] where convert( varchar(255), [' + @col + '] ) like ''%' + @data + '%''
'
exec(@sql)

fetch next from cur_tbl into @tbl, @col
end
close cur_tbl
deallocate cur_tbl


Credit to: http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_24142162.html

2 comments:


  1. it’s ok to show some appreciation and say ‘great post’
    .NET developer

    ReplyDelete
  2. Thank you for posting this has really helped me

    ReplyDelete