MS Sql Server 2000:多数据库查询

发布于 2024-07-14 02:59:43 字数 88 浏览 7 评论 0原文

我为每个部门都有单独的数据库。我在主数据库表中列出了所有部门列表。所有数据库都命名为 a1、a2 等现在我想从查询返回的所有部门数据库中获取员工详细信息。请帮助我

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞慾 2024-07-21 02:59:43

类似:

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)

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)
初心未许 2024-07-21 02:59:43

您可以像这样跨数据库获取表:-

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

You can fetch tables across DBs like this:-

SELECT * FROM a1..Employee
UNION ALL
SELECT * FROM a2..Employee
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文