通过表名 查询所有存在这个表的数据库
1 declare @tbname sysname 2 set @tbname='tb' 3 declare @dbname sysname,@sql nvarchar(4000),@re bit,@sql1 varchar(8000) 4 set @sql1='' 5 declare tb cursor for select name from master..sysdatabases 6 open tb 7 fetch next from tb into @dbname 8 while @@fetch_status=0 9 begin 10 set @sql='set @re=case when exists(select 1 from [' 11 +@dbname+']..sysobjects where xtype=''U'' and name=''' 12 +@tbname+''') then 1 else 0 end' 13 exec sp_executesql @sql,N'@re bit out',@re out 14 if @re=1 set @sql1=@sql1+' union all select '''+@dbname+'''' 15 fetch next from tb into @dbname 16 end 17 close tb 18 deallocate tb 19 set @sql1=substring(@sql1,12,8000) 20 exec(@sql1)