MS Sql Server 2000:Multiple database query

最后都变了- 提交于 2019-12-11 15:23:28

问题


I am having separate database for each dept.I have all depts list in a master database table.All database are named as a1,a2 etc Now i want to fetch the employee detail from all the dept databses returned by a query.pls help me


回答1:


something like:

select <columnlist>, '[databasename1]' AS dbname 
  from [databasename1].[owner].[table or view name]
UNION
select <columnlist>, '[databasename2]' AS dbname  
  from [databasename2].[owner].[table or view name]
UNION 
select <columnlist>, '[databasename3]' AS dbname  
  from [databasename3].[owner].[table or view name]

Implementation:

DECLARE @DBTable TABLE (ID INT, DBName VARCHAR(20), DBOwner VARCHAR(10))
INSERT INTO @DBTable
SELECT 1, 'a1', 'dbo' UNION
SELECT 2, 'a2', 'dbo' UNION
SELECT 3, 'a3', 'dbo' UNION
SELECT 4, 'a5', 'dbo' 

DECLARE @Table VARCHAR(100), @Columns VARCHAR(500), @SQL VARCHAR(8000)
SELECT @Table = 'Emloyee', @Columns = 'ID, Name, Phone', @SQL = ''
SELECT @SQL = @SQL + '
SELECT '+@Columns+', '''+DBName+''' AS Database FROM ['+DBName+'].['+DBOwner+'].['+@Table+'] UNION'
FROM @DBTable
SET @SQL = SUBSTRING(@SQL, 0, LEN(@SQL) - 5)
EXEC(@SQL)



回答2:


You can fetch tables across DBs like this:-

SELECT * FROM a1..Employee
UNION ALL
SELECT * FROM a2..Employee


来源:https://stackoverflow.com/questions/594256/ms-sql-server-2000multiple-database-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!