如何编写从不同数据库和不同服务器提取的查询 [英] How to write a query that pulls from different databases and different servers

查看:88
本文介绍了如何编写从不同数据库和不同服务器提取的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例的数据:



服务器A:

数据库-DBO1

表 - 名字

字段 - nameid,名称



服务器B:

数据库-DBO2

表格 - 工人

字段 - nameid,名称



我需要加入2个表格,但我不知道该如何去关于这样做。 C#和.Net4被标记,因为sql代码将在.net应用程序中连接到sqlserver数据库。



现在,如果有人可以发布一个非常简单的方式,包括示例,如何编写具有上述条件的查询。一个sql server查询应该足够了(还没有专注于C#)。我会尽力回答问题。谢谢!

I have data like the following example:

Server A:
Database- DBO1
Table - names
fields - nameid, name

Server B:
Database- DBO2
Table - Worker
fields - nameid, name

I need to inner join the 2 tables but am not sure how to go about doing it. C# and .Net4 are tagged because the sql code will be in a .net application which is connected to sqlserver database.

For now, if someone can post a very simple way, example included, on how write a query with the above conditions that would be great. A sql server query should suffice (not peoccupied with the C# just yet). I'll do my best to answer questions. Thanks!

推荐答案

您可以使用链接服务器执行此操作。要查找或创建链接服务器,请转到服务器对象 - >链接服务器。



现在从两个数据库中获取数据,你可以查询如下 -

You can do that using Linked Server. To find or create a Linked Server go to Server Objects --> Linked Servers.

Now to get data from both db, you can query like-
SELECT nameid,[name] FROM DBO1.dbo.names
UNION 
SELECT nameid,[name] FROM DBO2.dbo.Worker





希望,它有帮助:)



Hope, it helps :)


如果数据库位于同一个SQL中服务器实例和您使用的凭据可以访问这两个数据库,然后您可以使用多部分标识符来定义表。类似

If the databases are located in the same SQL Server instance and the credentials you use have access to both databases, then you can simply define the tables using multi-part identifier. Something like
SELECT  * 
FROM  DBO1.dbo.Names a
INNER JOIN DBO2.dbo.Worker b ON a.NameID = b.NameID;



如果需要访问另一个SQL Server实例,链接服务器将是最简单的解决方案,但这是不可能的,那么你可以使用 OPENROWSET [ ^ ]。类似


If you need to access another instance of SQL Server, linked server would be the easiest solution but of that's not possible, then you can perhaps use OPENROWSET[^]. Something like

SELECT  *
FROM  DBO1.dbo.Names a
INNER JOIN OPENROWSET('SQLNCLI', 
              'Server=AnotherServer;Trusted_Connection=yes;',
              'SELECT NameID, Name
               FROM DBO2.dbo.Worker') b 
      ON a.NameID = b.NameID;


这篇关于如何编写从不同数据库和不同服务器提取的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆