在当前数据库的所有表,所有字段查找字符串

来源:互联网 发布:程序员的数学 统计 pdf 编辑:程序博客网 时间:2024/04/30 17:54
/*
    search a string in all databaes tables and all fields
*/

if object_id('search_db') is not null
    drop proc search_db
go

create proc search_db
    @table nvarchar(100),
    @cond nvarchar(512)
as
declare hCForEach cursor global for
select sqlstmt =
'if exists (' + stmt + ')
    print ''' + replace(stmt, '''', '''''') + ''''
from(
    select stmt='select * from [' + TABLE_NAME + '] where convert(nvarchar, [' + COLUMN_NAME + ']) like ''' + @cond + ''''
    from INFORMATION_SCHEMA.COLUMNS A
    where (IsNull(@table, '') = '' or TABLE_NAME like @table) and DATA_TYPE <> 'image' and
        (SELECT TABLE_TYPE from INFORMATION_SCHEMA.TABLES B where A.TABLE_NAME = B.TABLE_NAME) = 'BASE TABLE'
) T

exec sp_msforeach_worker @command1 = N'?'
go

exec search_db '', '%HKG%'

drop proc search_db