How can I connect to an external database from a sql statement or a stored procedure?

[亡魂溺海] 提交于 2020-01-10 02:50:12

问题


When running a SQL statement or a stored procedure on a database, can you connect to an external database and pull data from there?

something like:

SELECT a.UserID, b.DataIWantToGet 
  FROM mydb.Users as a, externaldb.Data as b

回答1:


You'll need to setup a Linked Server instance. Then you can reference the external database as though it were a SQL Server database.




回答2:


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.,

SELECT database.owner.table for local data
SELECT server.database.owner.table for remote data

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...




回答3:


Yes, you can. You should take a look at linked servers for starters. You can also use OPENROWSET to hit them directly with no linked server.




回答4:


Easiest way :

  • Click connect to server
  • when it asks for server name use: 192.168.X.X,1433\SQLEXPRESS insted of YOURPC\SQLEXPRESS

(The ip and opened port of target sql server)

  • Type correct username and password
  • Done!


来源:https://stackoverflow.com/questions/1942228/how-can-i-connect-to-an-external-database-from-a-sql-statement-or-a-stored-proce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!