对整个数据库全部表的字段进行文本查找,返回的结果为字段名、表名、出现的次数
CREATE PROCEDURE Search_tablename
@strword varchar(50)
AS
BEGIN
set nocount on
create table #result
(
OID int not null identity,
ziduan varchar(50) null,
tablename varchar(50) null,
ziduanleixing varchar(50) null,
icount int null
)
declare @count int
,@ziduanname varchar(50)
,@tablename varchar(50)
,@ziduanleixing varchar(50)
,@sql Nvarchar(800)
declare cur_LocationList cursor fast_forward for
select a.name ,b.name,c.name from syscolumns a
inner join sysobjects b
on a.id=b.id and b.xtype='u' and lower(a.name) not in('desc','order','top','left','bottom','right')
inner join systypes c
on a.xtype=c.xusertype
and c.name in('varchar','char','nvarchar','nchar','decimal','float','int','money')
open cur_LocationList
fetch next from cur_LocationList into @ziduanname,@tablename,@ziduanleixing
while @@fetch_status = 0
begin
set @count=0
if @ziduanleixing='money'
set @sql='select @a=count(*) from ['+@tablename+'] where convert(varchar(20),['+@ziduanname+']) like ''%'+@strword+'%'''
else
set @sql='select @a=count(*) from ['+@tablename+'] where ['+@ziduanname+'] like ''%'+@strword+'%'''
--print @sql
exec sp_executeSql @sql,N'@a int output',@count output
--print @count
if @count>=1
begin
insert into #result(ziduan,tablename,icount,ziduanleixing) values (@ziduanname,@tablename,@count,@ziduanleixing)
end
fetch next from cur_LocationList into @ziduanname,@tablename,@ziduanleixing
end
close cur_LocationList
deallocate cur_LocationList
select ziduan as "字段名",tablename as "表名",icount as "出现次数",ziduanleixing as "字段类型" from #result
order by "表名","字段名"
drop table #result
set nocount off
END
GO
exec Search_tablename '欲查找值'