Skip to content

Instantly share code, notes, and snippets.

@FelicePollano
Last active July 31, 2023 13:54
Show Gist options
  • Save FelicePollano/bd1d5ae064285b7607b1a5f2b76aee58 to your computer and use it in GitHub Desktop.
Save FelicePollano/bd1d5ae064285b7607b1a5f2b76aee58 to your computer and use it in GitHub Desktop.
Search all table, all columns for a specific ( numeric ) value is SQLServer
declare @serchval varchar(20) = '12347'
declare @table_name varchar(max), @col_name varchar(max),@sql varchar(max)
create table #results (table_name varchar(100), column_name varchar(100))
declare crunch_all cursor forward_only for
select t.table_schema+'.'+t.table_name table_name,c.COLUMN_NAME col_name from INFORMATION_SCHEMA.TABLES t
inner join INFORMATION_SCHEMA.COLUMNS c on c.TABLE_NAME = t.TABLE_NAME and c.TABLE_SCHEMA = t.TABLE_SCHEMA
where c.DATA_TYPE in ('int','decimal','smallint','float','real')
open crunch_all
fetch next from crunch_all into @table_name,@col_name
while @@FETCH_STATUS = 0
begin
SET @sql = 'select '''+ @table_name+''''+','+''''+@col_name+''''+' from '+@table_name +' where '+@col_name+' ='+@serchval
--print @sql
insert into #results
exec(@sql)
fetch next from crunch_all into @table_name,@col_name
end
close crunch_all
deallocate crunch_all
select * from #results
drop table #results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment