首页 > 代码库 > 查找当前数据库服务器中某张表存在于哪个数据库中

查找当前数据库服务器中某张表存在于哪个数据库中

 1 --
 2 --查找当前数据库服务器中某张表存在于哪个数据库中,sqlserver2008测试通过
 3 --
 4 declare @tableName varchar(50)
 5 --这里设置要查询的表名字
 6 set @tableName=Products
 7  
 8 --清理临时表
 9 if object_id(tempdb..#tmpdbs) is not null Begin
10     drop table #tmpdbs
11 End
12 if object_id(tempdb..##tmpResults) is not null Begin
13     drop table ##tmpResults
14 End
15  
16 --手动创建全局临时表,下面插入时只能使用insert into ,不能使用select into ,后者会自动创建临时表
17 create table ##tmpResults(
18     DbName varchar(50),
19     Name varchar(50),
20     XType varchar(50)
21 )
22  
23 Select  Name,ROW_NUMBER() over(order by Name) as rowid into #tmpdbs  FROM Master..SysDatabases  Name
24 declare @dbName varchar(50)
25 declare @rowid int
26 declare @count int
27  
28 set @rowid=1
29 select @count=count(*) from #tmpdbs
30  
31 while @rowid <= @count
32 begin
33     --print(@rowid)
34     select @dbName=[Name] from #tmpdbs where rowid=@rowid
35     exec (insert into ##tmpResults Select ‘‘‘+@dbName+‘‘‘ as DbName,Name,xtype  FROM +@dbName+..SysObjects Where (XType=‘‘U‘‘ or XType=‘‘SN‘‘)  and Name=‘‘‘+@tableName+‘‘‘ ORDER BY Name)
36     set @rowid=@rowid+1
37 end
38  
39 --查看结果
40 select * from  ##tmpResults
41  
42 --清理临时表
43 if object_id(tempdb..#tmpdbs) is not null Begin
44     drop table #tmpdbs
45 End
46 if object_id(tempdb..##tmpResults) is not null Begin
47     drop table ##tmpResults
48 End

 

查找当前数据库服务器中某张表存在于哪个数据库中