有數據庫test1和數據庫test2。其中test1中有表 table1、table2;test2 中有表 table1。三個表的字段都為為:id、xingming、shijian、shuliang。接下來我們就以上面的條件為例來介紹跨數據庫查詢和跨表 查詢的方法。
SELECT *?
? FROM OPENROWSET('sqloledb',?
?'DRIVER={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=ccds',
?test1.dbo.table1)? where xingming='a'
? UNION?? all
SELECT *?
? FROM OPENROWSET('sqloledb',?
?'DRIVER={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=ccds',
?test2.dbo.table1)? where xingming='a'
?
執行后,出現報錯:?阻止了對組件 'Ad Hoc Distributed Queries' 的 STATEMENT 'OpenRowset/OpenDatasource' 的訪問,因為此組件已作為此服務器安全配置的一部分而被關閉
執行如下語句:
?啟用Ad Hoc Distributed Queries:
exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
??? 使用完成后,關閉Ad Hoc Distributed Queries:
exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure
exec sp_configure 'show advanced options',0
reconfigure