Mssql 跨域查询

有数据库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

原文地址:https://www.cnblogs.com/fer-team/p/5855643.html