sqlserver跨資料庫操作

2021-05-27 16:09:56 字數 1752 閱讀 9050

1、方法一:建立鏈結伺服器

--建立鏈結伺服器 

exec 

sp_addlinkedserver 

'srv_lnk','','sqloledb','遠端伺服器名或ip位址' 

exec 

sp_addlinkedsrvlogin 

'srv_lnk','false',null,'使用者名稱','密碼' 

go --查詢示例 

select 

*  from 

srv_lnk.資料庫名.dbo.表名 

--以後不再使用時刪除鏈結伺服器 

exec 

sp_dropserver 

'srv_lnk','droplogins' 

go2、方法二:

--如果只是臨時訪問,可以直接用openrowset 

--查詢示例 

select 

*  from 

openrowset('sqloledb' 

,'sql伺服器名';'使用者名稱';'密碼' 

,資料庫名.dbo.表名) 

但是預設情況下會報錯如下:

sql server 阻止了對元件 'ad hoc distributed queries' 的statement'openrowset/opendatasource' 的訪問,因為此元件已作為此伺服器安全配置的一部分而被關閉。系統管理員可以通過使用 sp_configure 啟用 'ad hoc distributed queries'.有關啟用 'ad hoc distributed queries' 的詳細資訊...

解決方法:

啟用ad hoc distributed queries:

exec sp_configure 'show advanced options',1

goreconfigure

goexec sp_configure 'ad hoc distributed queries',1

goreconfigure

go使用完成後,關閉ad hoc distributed queries:

exec sp_configure 'ad hoc distributed queries',0

goreconfigure

goexec sp_configure 'show advanced options',0

goreconfigure

go要是遠端的話,則需要啟動遠端伺服器的msdtc服務

--啟動遠端伺服器的msdtc服務 

exec 

master..xp_cmdshell 

'isql 

/s"xz" 

/u"sa" 

/p"" 

/q"exec  master..xp_cmdshell 

''net 

start 

msdtc'',no_output"',no_output 

--啟動本機的msdtc服務 

exec 

master..xp_cmdshell 

'net 

start 

msdtc',no_output

----方法3

資料庫1:aaa

資料庫2:bbb

資料庫名和表名之間放兩個點

select * from [aaa]..tablea a inner join [bbb]..tableb b on a.acountid = b.clientid

注意:必須是單個sql例項!

SQL Server 跨資料庫查詢

語句 select from 資料庫a.dbo.表a a,資料庫b.dbo.表b b where a.field b.field dbo 可以省略 如 select from 資料庫a.表a a,資料庫b.表b b where a.field b.field sqlserver資料庫 這句是對映乙個...

SQLServer 跨資料庫訪問

首先,你要知道跨資料庫訪問的語法,如下 select from openrowset sqloledb driver server 伺服器位址 uid sa pwd 密碼 資料庫名.dbo.表名 如果沒有啟用ad hoc distributed queries,查詢結果是出錯的,如下描述 exec ...

sql server 跨資料庫插入資料

公司專案改造,需要將以前的資料庫表記錄匯入到新的資料庫表中,結構不是完全相同。在跨庫的過程中,學到了不少東西。原來sqlserver 還有 鏈結伺服器的功能呢。建立鏈結伺服器exec sp addlinkedserver itsv sqloledb 遠端伺服器名或ip位址 exec sp addli...