declare @serverIP varchar(50) --伺服器IP地址
declare @serverOtherName varchar(50) --被訪問的伺服器別名
declare @loginUser varchar(50) --帳號
declare @loginPassword varchar(50) --密碼
set @serverIP = '118.8.28.9'
set @serverOtherName = 'newW'
set @loginUser = 'testUser'
set @loginPassword = '123'
--添加連結的伺服器
exec sp_addlinkedserver
@server=@serverOtherName,
@datasrc=@serverIP,
@srvproduct='',
@provider='SQLOLEDB'
--為連結的伺服器添加登陸
EXEC sp_addlinkedsrvlogin
@serverOtherName,
'false',
NULL,
@loginUser,
@loginPassword
--執行查詢
select * from [newW].dataBaseName.dbo.table1
--刪除連結的伺服器
IF EXISTS (SELECT srvname FROM master.dbo.sysservers srv WHERE srvid != 0 AND srvname = N'newW')
EXEC master.dbo.sp_dropserver @server=N'newW', @droplogins='droplogins'
select * from openquery(newW,'select top 5 * from table1')
select top 5 * from opendatasource('SQLOLEDB','Data Source=118.8.28.9;User ID=testUser;Password=123').HfOA2007.dbo.table1
select * from openrowset('MSDASQL','DRIVER={SQL Server};SERVER=118.8.28.9;UID=testUser;PWD=123','select top 5 * from table1')
/*
openquery方法和openrowset方法是直接傳遞分散式查詢,速度會比直接使用連結的伺服器要快。openquery和openrowset的區別在於openquery使用連結服務其,而openrowset不是。
在使用OpenRowSet()執行update命令時,應當將該函數作為要修改的表。如下:
update openrowset('MSDASQL','DRIVER={SQL Server};SERVER=118.8.28.9;UID=testUser;PWD=123','select * from table1 where id=1') set fieldName1='Hello'
*/