能够根据字段值,查找出该字段值位于数据库哪张表,甚至哪一行?
需求是这样的:
后台数据库是第三方提供的,能否根据前台查询到的某个字段值,
在数据库中定位出哪张表,甚至哪一行么?
比如说,我知道有一个值 "100" ,有没有办法可以一下查出数据库中都有哪些表中记录了"100" 这个值。
------解决方案--------------------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 #
------解决方案--------------------------------------第一种方法----------------------
CREATE PROC sp_ValueSearch
@value sql_variant, --要搜索的数据
@precision bit=1 --1=仅根据sql_variant中的数据类型查找对应类型的数据列.<>1,查询兼容的所有列,字符数据使用like匹配
AS
SET NOCOUNT ON
IF @value IS NULL RETURN
--数据类型处理
SELECT xtype INTO #t FROM systypes
WHERE name=SQL_VARIANT_PROPERTY(@value,N'BaseType')
--扩展数据类型及查询处理语句
DECLARE @sql nvarchar(4000),@sql1 nvarchar(4000)
IF @precision=1
SET @sql=CASE SQL_VARIANT_PROPERTY(@value,N'BaseType')
WHEN N'text' THEN N' LIKE N''%''+CAST(@value as varchar(8000))+''%'''
WHEN N'ntext' THEN N' LIKE ''%''+CAST(@value as nvarchar(4000))+''%'''
ELS