SQL中两台服务器间使用连接服务器

来源:互联网 发布:全民枪战数据查询 编辑:程序博客网 时间:2024/06/08 15:55
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

1:执行另一服务器上的存储过程

execOPENDATASOURCE(
        'SQLOLEDB',
        'DataSource=远程ip;UserID=sa;Password=密码'
        ).库名.dbo.存储过程名

2:将资料插入另一服务器上的表中

select*into本地库名..表名fromOPENDATASOURCE(
        'SQLOLEDB',
        'DataSource=远程ip;UserID=sa;Password=密码'
        ).库名.dbo.表名

insert本地库名..表名select*fromOPENDATASOURCE(
        'SQLOLEDB',
        'DataSource=远程ip;UserID=sa;Password=密码'
        ).库名.dbo.表名

或使用联结服务器:
EXECsp_addlinkedserver'别名','','MSDASQL',NULL,NULL,'DRIVER={};SERVER=远程名;UID=用户;PWD=密码;'


execsp_addlinkedsrvlogin @rmtsrvname='别名',@useself='false',@locallogin='sa',@rmtuser='sa',@rmtpassword='密码'
GO

(请注意上面的两步要同时运行)


然后你就可以如下:
select*from别名.库名.dbo.表名
insert库名.dbo.表名select*from别名.库名.dbo.表名
select*into库名.dbo.新表名from别名.库名.dbo.表名
go


 

3:

如果在事务里使用连接服务器要加上

分布式事务:
两边启动dtc

set XACT_ABORTon
setANSI_NULL_DFLT_ONon
setANSI_WARNINGSon

BEGINDISTRIBUTEDTRANSACTION
select* fromOPENDATASOURCE('MSDASQL','DRIVER={SQLServer};SERVER=ip;UID=sa;PWD=密码;').pubs.dbo.jobs
committran

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>