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