本地与远程数据库协同操作(数据库分布式查询)

有时候我们需要将远程两台服务器的数据进行修改、更新等操作。这时希望在一台服务器的方便的查询另一台服务器的表。下面就是操作的方法与步骤:
一、添加、登录远程数据库服务器

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'

posted @ 2009-08-26 11:14  吾非无心  阅读(326)  评论(0编辑  收藏  举报