在日常中会遇上多个不同服务器上数据库上的数据同步问题
--1.新建远程数据库链接
declare @ServerDb nvarchar(50)
declare @ServerIP nvarchar(50)
declare @ServerUSER nvarchar(50)
declare @ServerPWD nvarchar(50)
set @ServerDb='otherServer'
set @ServerIP='数据库服务名称'
set @ServerUSER='登录名'
set @ServerPWD='表名'
if(exists(select * from sys.servers where name=@ServerDb))
begin
--删除运行本地与远程之间的用户映射
execute sys.sp_droplinkedsrvlogin @rmtsrvname='otherServer',@locallogin=null
--删除链接服务器
execute sys.sp_dropserver @server='otherServer',@droplogins='droplogins'
end
--创建远程链接服务器
execute sys.sp_addlinkedserver @server='otherServer', --被访问的服务器别名
@srvproduct='',
@provider='SQLOLEDB',
@datasrc=@ServerIP --被访问的服务器地址(IP地址,端口号\服务器名称)
--创建本地用户与远程服务器中用户之间的映射
execute sys.sp_addlinkedsrvlogin @rmtsrvname='otherServer', --被访问的服务器别名
@useself='false', --是否通过模拟本地登录名或显式提交登录名和密码来连接到远程服务器
@locallogin=null, --本地登录
@rmtuser=@ServerUSER, --用户名
@rmtpassword=@ServerPWD --密码
go
--建立完成之后就可以正常使用了
select * from otherServer.[数据库名].dbo.表名称 --连接服务器别名.数据库名称.dbo.表名称