SQL Server分布式查询
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'
*/