如何从 sql 语句或存储过程连接到外部数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1942228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I connect to an external database from a sql statement or a stored procedure?
提问by Matt
When running a SQL statement or a stored procedure on a database, can you connect to an external database and pull data from there?
在数据库上运行 SQL 语句或存储过程时,是否可以连接到外部数据库并从中提取数据?
something like:
就像是:
SELECT a.UserID, b.DataIWantToGet
FROM mydb.Users as a, externaldb.Data as b
回答by OMG Ponies
You'll need to setup a Linked Server instance. Then you can reference the external database as though it were a SQL Server database.
您需要设置一个链接服务器实例。然后,您可以像引用 SQL Server 数据库一样引用外部数据库。
回答by Chris J
Yep -- there's two methods: either use the function OPENROWSET
, or use linked servers. OPENROWSET is useful for ad-hoc single statements, but if you're going to be doing this regularly, read up on linked servers as they allow you to do exactly what you've specified in your SQL Statement ... e.g.,
是的 - 有两种方法:使用函数OPENROWSET
或使用链接服务器。OPENROWSET 对于临时的单个语句很有用,但如果您要定期执行此操作,请阅读链接服务器,因为它们允许您完全按照您在 SQL 语句中指定的内容进行操作……例如,
SELECT database.owner.table
for local dataSELECT server.database.owner.table
for remote data
SELECT database.owner.table
用于本地数据SELECT server.database.owner.table
用于远程数据
And yes, you can mix and match to do joins twixt local and remote. Note though that you'll need to be caureul if you do joins against large tables that exist on the remote server as the query could take a long time to exexute...
是的,您可以混合搭配以进行本地和远程连接。请注意,如果您对远程服务器上存在的大型表进行联接,则需要小心,因为查询可能需要很长时间才能执行...
回答by Scott Ivey
Yes, you can. You should take a look at linked serversfor starters. You can also use OPENROWSETto hit them directly with no linked server.
是的你可以。对于初学者,您应该查看链接服务器。您还可以使用OPENROWSET在没有链接服务器的情况下直接命中它们。
回答by Disco4uf
Easiest way :
最简单的方法:
- Click connect to server
- when it asks for server name use: 192.168.X.X,1433\SQLEXPRESSinsted of YOURPC\SQLEXPRESS
- 点击连接到服务器
- 当它要求服务器名称时使用: 192.168.XX,1433\SQLEXPRESS instedof YOURPC\SQLEXPRESS
(The ip and opened port of target sql server)
(目标sql server的ip和打开的端口)
- Type correct username and password
- Done!
- 输入正确的用户名和密码
- 完毕!