简体   繁体   English

从两个不同的数据库(同一服务器)中选择 2 个不同的表的 SQL 语句

[英]SQL statement to select from 2 different tables, from two different databases (same server)

How do I select from multiple tables in different databases on the same server?如何从同一服务器上不同数据库的多个表中进行选择?

Also, Is there a way to have an identifying marker so I could see where the results came from?另外,有没有办法有一个识别标记,这样我就可以看到结果的来源?

So for example:例如:

SELECT db1.table1.name, db2.table2.name, fromTbl
FROM db1.table1, db2.table2
WHERE db1.table1.name LIKE '%j%' OR db2.table2.name LIKE '%j%'

So in this case, I'm selecting the names from 2 different databases and tables.所以在这种情况下,我从 2 个不同的数据库和表中选择名称。 I'm doing a wildcard search on those names and the fromTbl would let me know where the results came from?我正在对这些名称进行通配符搜索,而 fromTbl 会让我知道结果来自哪里?

4    john smith    4    555.555.5555    table1
17   joe schmoe    17   555.555.5555    table2
11   james doe     11   555.555.5555    table1

I'm using SQL Server 2005.我正在使用 SQL Server 2005。

You could use a UNION ALL and add in the database name like:您可以使用 UNION ALL 并添加数据库名称,例如:

SELECT [columns_list], 'db1.schema.table1.name' AS [fromTbl]
FROM db1.schema.table1
WHERE db1.schema.table1.name LIKE '%j%' 
UNION ALL
SELECT [columns_list], 'db2.schema.table2.name' AS [fromTbl]
FROM db2.schema.table2
WHERE db2.schema.table2.name LIKE '%j%'

This will only work if the columns in the tables have the same column types (as your example suggests) else UNION will not work.这仅在表中的列具有相同的列类型(如您的示例所示)时才有效,否则 UNION 将不起作用。

Doing a union seems like your best bet here.在这里建立工会似乎是您最好的选择。 A union will combine the results of two queries.联合将组合两个查询的结果。

select name, 'table1' as fromTbl
from db1.schema.table1
where name like '%j%'

union --or union all depending on what you want

select name, 'table2' as fromTbl
from db2.schema.table2
where name like '%j%'

试试这个: SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a UNION SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection =yes;','SELECT * FROM Table1') AS a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM