SQL Server串連遠端資料源的基本方法有下面三種:
OPENDATASOURCE: The OPENDATASOURCE function is used to specify connection information for a remote data source by specifying the OLE DB provider and an initialization string. OPENDATASOURCE can be used directly within a SELECT, INSERT, UPDATE, or DELETE statement.
OPENROWSET: The OPENROWSET function is used to specify connection information for a remote data source and the name of an object that will return a result set (such as a stored procedure) or a query that will return a result set. Like OPENDATASOURCE, OPENROWSET can be used directly within a SELECT, INSERT, UPDATE, or DELETE statement.
Linked servers: A linked server is an object within SQL Server that defines the connection properties of another SQL Server. When defined, queries can connect to the remote server using a four-part name, such asSQLSrv1.AdventureWorks.person.ContactThe four-part name identifies the server (SQLSrv1), the database (AdventureWorks), the schema (Person), and the object (Contact table). Linked servers are explored in more depth in the final section of this chapter. 其中OPENDATASOURCE和OPENROWSET方法一般用來做臨時查詢(ad hoc query),如果需要經常的查詢遠端資料,則建議建立linked servers。但是,預設情況ad hoc query 是禁用的,需要手動啟動:sp_configure ‘show advanced options’, 1;GORECONFIGURE;GOsp_configure ‘Ad hoc Distributed Queries’, 1;GORECONFIGURE; 然後,就可以使用OPENDATASOURCE 查詢遠端資料庫了,OPENDATASOURCE 基本文法如下:OPENDATASOURCE ( provider_name, init_string )。範例程式碼如下:SELECT *FROM OPENDATASOURCE(‘SQLNCLI’,‘Data Source=SQL08;Integrated Security=SSPI’).Sales.dbo.Customers上述代碼從SQL08伺服器上讀取Sales資料庫的Customers表的內容。 也可以通過OPENROWSET方法查詢遠端資料庫,OPENROWSET和OPENDATASOURCE方法相似,基本的差異是OPENROWSET總是返回結果集,而OPENDATASOURCE方法除了可以返回結果集(Result Set)外,也可以用來執行預存程序。OPENROWSET 基本文法如下:OPENROWSET ( provider_name, provider_string )範例程式碼:SELECT rs.*FROM OPENROWSET(‘SQLNCLI’,‘Server=SQL08;Trusted_Connection=yes;’,‘SELECT * FROM Sales.dbo.Customers’) AS rs;
使用Linked Server如果你計劃多次查詢外部或遠端資料源,建議建立linked server。儘管建立linked server需要一點時間,但是一旦建立後,你可以非常方便地使用four-part 名稱來訪問遠端資料源。
建立和配置linked server一般需要兩步:第一步是建立linked server。可以通過sp_addlinkserver系統預存程序來建立linked server,基本文法如下:sp_addlinkedserver [ @server= ] ‘server’ [ , [@srvproduct= ] ‘product_name’ ][ , [ @provider= ] ‘provider_name’ ][ , [ @datasrc= ] ‘data_source’ ][ , [ @location= ] ‘location’ ][ , [ @provstr= ] ‘provider_string’ ][ , [ @catalog= ] ‘catalog’ ] 樣本指令碼如下所示:EXEC sp_addlinkedserver @server = 'SQLSRV3', @srvProduct = N'SQL Server' 也可以通過SQL Server的管理介面,來建立linked server,如所示: