本地与远程数据库协同操作(数据库分布式查询)
一、添加、登录远程数据库服务器
exec sp_addlinkedserver
@server='www',--被访问的服务器别名
@srvproduct='',
@provider='SQLOLEDB',
@datasrc='xxx.xxx.xxx.xxx,端口'
EXEC sp_addlinkedsrvlogin
'www', --被访问的服务器别名
'false',
NULL,
'sa', --帐号
'************' --密码
二、使用
1、select * from www.数据库名.dbo.表名
2、
declare @articleId bigint;
declare @uploadtime datetime;
DECLARE MyUserCursor CURSOR FOR
select articleid from AAAAA;
OPEN MyUserCursor;
FETCH NEXT FROM MyUserCursor INTO @articleId;
WHILE @@FETCH_STATUS=0
BEGIN
select @uploadtime=uploadtime from www.XXXXXX.dbo.BBBBBB where fileId=@articleId;
update AAAAA set uploadtime=@uploadtime where articleid=@articleId;
FETCH NEXT FROM MyUserCursor INTO @articleId;
END
CLOSE MyUserCursor;
DEALLOCATE MyUserCursor;
三、移除远程服务器
exec sp_droplinkedsrvlogin @rmtsrvname = 'www', @locallogin = NULL
exec sp_dropserver @server = 'www'