2012-08-13 49 views
0

例如我有數據庫A,並且我知道在其中一個表中的某個地方是值爲C的字段B,但是我不知道該字段名稱和表格。TSQL在Haystack中查找Needle

問題:在哪個表格和字段中檢測(?)的最快方法是C值?

+2

這可能是有用非常有用 - http://stackoverflow.com/a/11676778/16391。在您的閒暇時間重做。 – StingyJack 2012-08-13 13:33:59

+0

SSMS工具包具有此功能。 – 2012-08-13 13:41:23

+0

謝謝馬丁!我認爲這是一個很好的選擇,但SSMS Tools有什麼許可? (GPL?) – undefined 2012-08-13 13:47:19

回答

1

我很久以前寫這個劇本,它一直是逆向工程

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+']='''[email protected] +'''' + ' 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 
+0

最後我有足夠的聲望給你一個 – undefined 2013-02-26 15:01:42

+0

@undefined很高興聽到你喜歡我的腳本 – 2013-02-26 22:31:42