在sqlserver資料庫中查詢所有表的任意欄位中某個值(例如值為a)

來源:互聯網
上載者:User




CREATE TABLE qResults (tName nvarchar(370), cname nvarchar(3630),[count] int)

declare @tname nvarchar(200)
declare @cname nvarchar(200)

declare @countOut nvarchar(200)
declare @sql nvarchar(max)
declare c_search cursor for
select t.name,c.name from sysobjects t inner join syscolumns c on t.id=c.id where t.type='u'  and c.xtype in(56,167,175,231,239) order by t.name --xtype 這個地方限制類型為int varchar char nvarchar nchar 五種類型
open c_search
fetch next from c_search into @tname,@cname
while @@FETCH_STATUS=0
begin
  
   set @sql=N'select @countx=COUNT(*) from '+@tname +' where [' +@cname +'] =''a' '
  
   print @sql
   EXECUTE sp_executesql @sql,N'@countx nvarchar(200) out ', @countx=@countOUT OUT

   insert into qResults values (@tname,@cname,@countOUT)

  
   fetch next from c_search into @tname,@cname
end
select tName 'Table',cname 'Field' from qResults where [count]>0 order by tname
close c_search
deallocate c_search

drop table qResults
 



相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.