设为首页 加入收藏

TOP

查找当前数据库服务器中某张表存在于哪个数据库中
2015-11-21 01:40:57 来源: 作者: 【 】 浏览:1
Tags:查找 当前 数据库 服务器 张表存 在于 哪个
--
--查找当前数据库服务器中某张表存在于哪个数据库中,sqlserver2008测试通过
--
declare @tableName varchar(50)
--这里设置要查询的表名字
set @tableName='Products'

--清理临时表
if object_id('tempdb..#tmpdbs') is not null Begin
    drop table #tmpdbs
End
if object_id('tempdb..##tmpResults') is not null Begin
    drop table ##tmpResults
End

--手动创建全局临时表,下面插入时只能使用insert into ,不能使用select into ,后者会自动创建临时表
create table ##tmpResults(
    DbName varchar(50),
    Name varchar(50),
    XType varchar(50)
)

Select  Name,ROW_NUMBER() over(order by Name) as rowid into #tmpdbs  FROM Master..SysDatabases  Name
declare @dbName varchar(50)
declare @rowid int
declare @count int

set @rowid=1
select @count=count(*) from #tmpdbs

while @rowid <= @count
begin
    --print(@rowid)
    select @dbName=[Name] from #tmpdbs where rowid=@rowid
    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')
    set @rowid=@rowid+1
end

--查看结果
select * from  ##tmpResults

--清理临时表
if object_id('tempdb..#tmpdbs') is not null Begin
    drop table #tmpdbs
End
if object_id('tempdb..##tmpResults') is not null Begin
    drop table ##tmpResults
End

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇查看数据库所有表的所有字段 下一篇SqlServer2012OFFSET和FETCH子句..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: