SQL-根据某个值查询在哪个表出现过

declare @cloumns varchar(5000) declare @tablename varchar(4000) declare @str varchar(4000) declare @counts int declare @sql nvarchar(2000)

--定义游标 declare MyCursor Cursor For 

Select a.name as Columns, b.name as TableName from syscolumns a,sysobjects b,systypes c  where a.id = b.id and b.type = 'U'  and a.xtype=c.xtype and c.name like '%char%' --设置需要查询的值 set @str='D47'

--打开游标 Open MyCursor Fetch next From MyCursor Into @cloumns,@tablename While(@@Fetch_Status = 0) Begin  set @sql='select  @tmp_counts=count(*) from ' +@tablename+ ' where ' +@cloumns+' = ''' +@str+ ''''

execute sp_executesql  @sql,N'@tmp_counts int out',@counts out

 if @counts>0

 begin  print 'TableName:'+@tablename+',Coloums:'+@cloumns  end

Fetch next From MyCursor Into @cloumns,@tablename

End --关闭游标 Close MyCursor --释放游标 Deallocate MyCursor

posted @ 2019-09-18 11:59    阅读(906)  评论(0编辑  收藏  举报