例如,我有数据库 A,并且我知道其中一个表中的某处是字段 B,其值为 C,但是我不知道该字段名称或表。
问题:在哪个表和字段中检测 (?) 值 C 的最快方法是什么?
我很久以前写过这个脚本,它对逆向工程非常有用
set nocount off
declare @searchvalue varchar(100)
set @searchvalue = 'text to find'
create table #tt (table_name varchar(64), column_name varchar(64), count int)
select * into #t from
(
select 'select ''' + a.table_name + ''' ''table_name'',''' + a.column_name + ''' ''column_name'', count(*) count from [' + a.table_name +'] where [' +a.column_name+']='''+@searchvalue +'''' + ' group by ['+ a.column_name+']' sqlstring
from INFORMATION_SCHEMA.COLUMNS a
join
INFORMATION_SCHEMA.TABLES b
on a.table_name = b.table_name
and b.table_type = 'base table'
where data_type like '%char'
) a
--loop cursor
Declare @sqlstring as nvarchar(500)
Declare SqlCursor CURSOR FAST_FORWARD FOR
SELECT sqlstring FROM #t
OPEN SqlCursor
FETCH NEXT FROM SqlCursor
INTO @sqlstring
WHILE @@FETCH_STATUS = 0
BEGIN
-- do row specific stuff here
insert #tt
exec(@sqlstring)
FETCH NEXT FROM SqlCursor
INTO @sqlstring
END
CLOSE SqlCursor
DEALLOCATE SqlCursor
select * from #tt
drop table #tt
drop table #t