根据内容在SQL中使用到的相关表和字段

背景:
一个SQL数据库,N多个表,只知道其中某个字段的值,不知道这个字段名,也不知道在哪个表里边。想要查询在哪个表里的哪个字段。
代码:

declare @str varchar(100) 
set @str='字符串' --要搜索的字符串
declare @s varchar(8000) 
declare tb cursor local for 
select s='if exists(select 1 from ['+b.name+'] where ['+a.name+'] like ''%'+@str+'%'') 
print ''所在的表及字段: ['+b.name+'].['+a.name+']''' 
from syscolumns a join sysobjects b on a.id=b.id 
where b.xtype='U' and a.status>=0 
and a.xusertype in(175,239,231,167) 
open tb 
fetch next from tb into @s 
while @@fetch_status=0 
begin 
exec(@s) 
fetch next from tb into @s 
end 
close tb 
deallocate tb


关键词: SQL

网友评论

发表评论