我为每个部门都有单独的数据库。我在主数据库表中有所有depts列表。所有数据库都命名为a1,a2等现在我想从查询返回的所有dept数据库中获取员工详细信息。请帮助我
答案 0 :(得分:4)
类似的东西:
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]
实现:
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)
答案 1 :(得分:1)
您可以在DB之间获取表格,如下所示: -
SELECT * FROM a1..Employee
UNION ALL
SELECT * FROM a2..Employee