不同服务器数据库之间的数据操作

use SVTCCData

/*******不同服务器数据库之间的数据操作*********/

--创建链接服务器
exec sp_addlinkedserver  'ITSV', '', 'SQLOLEDB', 'DBSeverMSSQL2008'
exec sp_addlinkedsrvlogin  'ITSV', 'false',null, 'sa', '123321'
set xact_abort on
----如果TableB有ID列,则需要加上这么一句
SET IDENTITY_INSERT TableB ON

--查询示例
select * from ITSV.SCJZData.dbo.[2014TestRemote]
 
--导入示例
insert into [2014TestRemote](ID,name,phone) select ID,name,phone from ITSV.SCJZData.dbo.[2014TestRemote]
 
--以后不再使用时删除链接服务器
exec sp_dropserver  'ITSV ', 'droplogins'

/*******连接远程/局域网数据(openrowset/openquery/opendatasource)*********/
  /********openrowset**********/

--启用Ad Hoc Distributed Queries:
exec sp_configure 'show advanced options',1 --开启高级配置
reconfigure WITH OVERRIDE
exec sp_configure 'Ad Hoc Distributed Queries',1  --开启即席查询
reconfigure  WITH OVERRIDE

--查询示例
select * from openrowset( 'SQLOLEDB', 'DBSeverMSSQL2008'; 'sa'; '123321',SCJZData.dbo.[2014TestRemote])
 
--生成本地表
select * into 表 from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)
 
--把本地表导入远程表
insert openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) select * from 本地表
 
--更新本地表
update b set b.列A=a.列A from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)as a inner join 本地表 b on a.column1=b.column1

--使用完成后,关闭Ad Hoc Distributed Queries:
exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure WITH OVERRIDE
exec sp_configure 'show advanced options',0
reconfigure WITH OVERRIDE

  /********openquery用法需要创建一个连接**********/
 
--首先创建一个连接创建链接服务器
exec sp_addlinkedserver  'ITSV', '', 'SQLOLEDB', 'DBSeverMSSQL2008'
exec sp_addlinkedsrvlogin  'ITSV', 'false',null, 'sa', '123321'
--查询
select * FROM openquery(ITSV,  'SELECT *  FROM SCJZData.dbo.[2014TestRemote] ')
--把本地表导入远程表
insert openquery(ITSV,  'SELECT *  FROM SCJZData.dbo.[2014TestRemote] ') select * from [2014TestRemote]

--更新本地表
update b set b.列B=a.列B FROM openquery(ITSV,  'SELECT * FROM 数据库.dbo.表名 ') as a  inner join 本地表 b on a.列A=b.列A

--以后不再使用时删除链接服务器
exec sp_dropserver  'ITSV ', 'droplogins'

  /********opendatasource/openrowset **********/
  
SELECT  * FROM  opendatasource( 'SQLOLEDB',  'Data Source=DBSeverMSSQL2008;User ID=sa;Password=123321' ).test.dbo.roy_ta
--把本地表导入远程表
insert opendatasource( 'SQLOLEDB',  'Data Source=DBSeverMSSQL2008;User ID=sa;Password=123321').SCJZData.dbo.[2014TestRemote] select * from [2014TestRemote] 

原文地址:https://www.cnblogs.com/hlxt548826/p/3945382.html