SQL - 根据字段值查找表名和字段名
declare @searchstr nvarchar(500)
set @searchstr ='100' --这里是你要查的字符内容
declare @t varchar(255),@c varchar(255)
create table # (name varchar(256),cols varchar(4000))
declare table_cursor cursor for
select a.name,b.name from sysobjects a,syscolumns b ,systypes c
where a.id=b.id and a.xtype='u' and b.xtype=c.xtype
and c.name in ('char','nchar','varchar','nvarchar','text','next')
open table_cursor fetch next from table_cursor
into @t,@c
while(@@fetch_status=0)
begin
exec('
set nocount on
if exists(select top 1 1 from [' + @t + '] where cast([' + @c + '] as varchar(8000)) like ''%'+@searchstr+'%'')
begin
if not exists(select 1 from # where name='''+@t+''')
insert into # select '''+@t+''','''+@c+'''
else
update # set cols=cols+'','+@c+''' where name='''+@t+'''
--select '+@c+' from [' + @t + '] where [' + @c + '] like ''%'+@searchstr+'%''
end
')
fetch next from table_cursor into @t,@c
end
close table_cursor deallocate table_cursor;
select name as '表名',cols as '列名' from #
drop table #
http://www.myexception.cn/sql-server/1599429.html
浙公网安备 33010602011771号