/*--------------------
-- 运行示例: Pro_LinkServer 'dbserver','192.168.1.1','sa','sapassword'
-- 运行后操作数据库: select * from db.pubs.dbo.titles
-- 参数:
-- @linknm :链接别名
-- @rmserv :链接地址
-- @rmuser :用户名称
-- @rmpawd :用户密码
---------------------*/
CREATE procedure HD_AddLinkServer
@linknm sysname,
@rmserv sysname,
@rmuser sysname,
@rmpawd sysname,
@flag tinyint=0 --0:add 1:drop 2:list
as
begin
if @flag!=2 and isnull(@linknm,'')=''
begin
raiserror('链接服务器名不能为空。',16,-1)
return
end
if @flag=0 and isnull(@rmuser,'')=''
begin
raiserror('远程登陆用户名不能为空。',16,-1)
return
end
declare @err int
if @flag=0
begin
if isnull(@rmserv,'')='' select @rmserv='127.0.0.1'
exec @err=master.dbo.sp_addlinkedserver @linknm
if @err=0
begin
exec @err=master.dbo.sp_serveroption @linknm,'use remote collation','false'
if isnull(@rmserv,'') not in ('',@linknm)
exec @err=master.dbo.sp_setnetname @linknm,@rmserv
if @err=0
exec @err=master.dbo.sp_addlinkedsrvlogin @linknm,'false',null,@rmuser,@rmpawd
end
end else
if @flag=1
begin
exec @err=master.dbo.sp_dropserver @linknm,'droplogins'
end else
if @flag=2
begin
exec @err=master.dbo.sp_helpserver
select * from master.dbo.sysservers
end
if @err=0 print 'Sql server link success' else print 'Sql server link fail'
end
GO
-- 运行示例: Pro_LinkServer 'dbserver','192.168.1.1','sa','sapassword'
-- 运行后操作数据库: select * from db.pubs.dbo.titles
-- 参数:
-- @linknm :链接别名
-- @rmserv :链接地址
-- @rmuser :用户名称
-- @rmpawd :用户密码
---------------------*/
CREATE procedure HD_AddLinkServer
@linknm sysname,
@rmserv sysname,
@rmuser sysname,
@rmpawd sysname,
@flag tinyint=0 --0:add 1:drop 2:list
as
begin
if @flag!=2 and isnull(@linknm,'')=''
begin
raiserror('链接服务器名不能为空。',16,-1)
return
end
if @flag=0 and isnull(@rmuser,'')=''
begin
raiserror('远程登陆用户名不能为空。',16,-1)
return
end
declare @err int
if @flag=0
begin
if isnull(@rmserv,'')='' select @rmserv='127.0.0.1'
exec @err=master.dbo.sp_addlinkedserver @linknm
if @err=0
begin
exec @err=master.dbo.sp_serveroption @linknm,'use remote collation','false'
if isnull(@rmserv,'') not in ('',@linknm)
exec @err=master.dbo.sp_setnetname @linknm,@rmserv
if @err=0
exec @err=master.dbo.sp_addlinkedsrvlogin @linknm,'false',null,@rmuser,@rmpawd
end
end else
if @flag=1
begin
exec @err=master.dbo.sp_dropserver @linknm,'droplogins'
end else
if @flag=2
begin
exec @err=master.dbo.sp_helpserver
select * from master.dbo.sysservers
end
if @err=0 print 'Sql server link success' else print 'Sql server link fail'
end
GO
删除链接:
/*******************************
-- 功能:
-- 建立SqlServer数据库链接映射
-- 参数说明:
-- @SqlServer : 服务器IP地址/服务器别名
********************************/
Create Proc HD_DropLinkServer
@SqlServer nvarchar(50)
AS
Exec sp_dropserver @SqlServer , 'droplogins'
GO
-- 功能:
-- 建立SqlServer数据库链接映射
-- 参数说明:
-- @SqlServer : 服务器IP地址/服务器别名
********************************/
Create Proc HD_DropLinkServer
@SqlServer nvarchar(50)
AS
Exec sp_dropserver @SqlServer , 'droplogins'
GO
链接建立完成后应用例子:
select * from [dbserver].[pubs].[dbo].[titles]