標籤:
SQLServer跨伺服器訪問資料庫(openrowset/opendatasource/openquery)
1、啟用Ad Hoc Distributed Queries
在使用openrowset/opendatasource前搜先要啟用Ad Hoc Distributed Queries服務,因為這個服務不安全所以SqlServer預設是關閉的
啟用Ad Hoc Distributed Queries的方法
SQL Server 阻止了對組件 ‘Ad Hoc Distributed Queries‘ 的 STATEMENT‘OpenRowset/OpenDatasource‘
的訪問,因為此組件已作為此伺服器安全配置的一部分而被關閉。系統管理員可以通過使用
sp_configure 啟用 ‘Ad Hoc Distributed Queries‘。有關啟用 ‘Ad Hoc Distributed Queries‘ 的詳細
資訊,請參閱 SQL Server 聯機叢書中的 "介面區配置器"。
啟用Ad Hoc Distributed Queries的方法,執行下面的查詢語句就可以了:
exec sp_configure ‘show advanced options‘,1
reconfigure
exec sp_configure ‘Ad Hoc Distributed Queries‘,1
reconfigure
使用完畢後,記得一定要要關閉它,因為這是一個安全隱患,切記執行下面的SQL語句
exec sp_configure ‘Ad Hoc Distributed Queries‘,0
reconfigure
exec sp_configure ‘show advanced options‘,0
reconfigure
2、使用樣本
--建立連結的伺服器
exec sp_addlinkedserver ‘ITSV ‘, ‘ ‘, ‘SQLOLEDB ‘, ‘遠程伺服器名或ip地址 ‘
exec sp_addlinkedsrvlogin ‘ITSV ‘, ‘false ‘,null, ‘使用者名稱 ‘, ‘密碼 ‘
--查詢樣本
select * from ITSV.資料庫名.dbo.表名
--匯入樣本
select * into 表 from ITSV.資料庫名.dbo.表名
--以後不再使用時刪除連結的伺服器
exec sp_dropserver ‘ITSV ‘, ‘droplogins ‘
--串連遠程/區域網路資料(openrowset/openquery/opendatasource)
--1、openrowset
--查詢樣本
select * from openrowset( ‘SQLOLEDB ‘, ‘sql伺服器名 ‘; ‘使用者名稱 ‘; ‘密碼 ‘,資料庫名.dbo.表名)
--產生本地表
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
--openquery用法需要建立一個串連
--首先建立一個串連建立連結的伺服器
exec sp_addlinkedserver ‘ITSV ‘, ‘ ‘, ‘SQLOLEDB ‘, ‘遠程伺服器名或ip地址 ‘
--查詢
select *
FROM openquery(ITSV, ‘Select * FROM 資料庫.dbo.表名 ‘)
--把本地表匯入遠端資料表
insert openquery(ITSV, ‘Select * FROM 資料庫.dbo.表名 ‘)
select * from 本地表
--更新本地表
update b
set b.列B=a.列B
FROM openquery(ITSV, ‘Select * FROM 資料庫.dbo.表名 ‘) as a
inner join 本地表 b on a.列A=b.列A
--3、opendatasource/openrowset
Select *
FROM opendatasource( ‘SQLOLEDB ‘, ‘Data Source=ip/ServerName;User ID=登陸名;Password=密碼 ‘ ).test.dbo.roy_ta
--把本地表匯入遠端資料表
insert opendatasource( ‘SQLOLEDB ‘, ‘Data Source=ip/ServerName;User ID=登陸名;Password=密碼 ‘).資料庫.dbo.表名
select * from 本地表
SQLServer跨伺服器訪問資料庫(openrowset/opendatasource/openquery)