有時候我們想通過一個值知道這個值來自數(shù)據(jù)庫的哪個表以及哪個字段,在網(wǎng)上搜了一下,找到一個比較好的方法,通過一個存儲過程實現(xiàn)的。只需要傳入一個想要查找的值,即可查詢出這個值所在的表和字段名。
前提是要將這個存儲過程放在所查詢的數(shù)據(jù)庫。
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技術(shù)專欄