有时候我们想通过一个值知道这个值来自数据库的哪个表以及哪个字段,在网上搜了一下,找到一个比较好的方法,通过一个存储过程实现的。只需要传入一个想要查找的值,即可查询出这个值所在的表和字段名。
前提是要将这个存储过程放在所查询的数据库。
create procedure [dbo].[sp_findvalueindb]
(
@value varchar(1024)
)
as
begin
-- set nocount on added to prevent extra result sets from
-- interfering with select statements.
set nocount on;
declare @sql varchar(1024)
declare @table varchar(64)
declare @column varchar(64)
create table #t (
tablename varchar(64),
columnname varchar(64)
)
declare tables cursor
for
select o.name, c.name
from syscolumns c
inner join sysobjects o on c.id = o.id
where o.type = 'u' and c.xtype in (167, 175, 231, 239)
order by o.name, c.name
open tables
fetch next from tables
into @table, @column
while @@fetch_status = 0
begin
set @sql = 'if exists(select null from [' + @table + '] '
set @sql = @sql + 'where rtrim(ltrim([' + @column + '])) like ''%' + @value + '%'') '
set @sql = @sql + 'insert into #t values (''' + @table + ''', '''
set @sql = @sql + @column + ''')'
exec(@sql)
fetch next from tables
into @table, @column
end
close tables
deallocate tables
select *
from #t
drop table #t
end
更多信息请查看IT技术专栏