假如有一台數據庫服務器,里面有很多庫,而自己對這些庫結構又不是很了解(比如到了一家新公司),想查找一張表在哪的話,可以借助下面這段SQL語句.
-- --查找當前數據庫服務器中某張表存在於哪個數據庫中,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
