OPENROWSET 用法
时间: 2023-08-21 09:35:57 浏览: 57
OPENROWSET 是 SQL Server 提供的一个用于连接到外部数据源的函数,可以通过它来查询、导入、导出外部数据源的数据。OPENROWSET 语法如下:
```
OPENROWSET ( provider_name, init_string, { query | 'query' } )
```
其中,provider_name 是外部数据源的 OLE DB 提供程序名称,init_string 是用于初始化外部数据源连接的字符串,可以是一个连接字符串或者其他初始化选项,query 是要执行的查询语句。
如果要使用 OPENROWSET 函数查询外部数据源的数据,可以使用以下语法:
```
SELECT *
FROM OPENROWSET('provider_name', 'init_string', 'SELECT * FROM external_table')
```
其中,'provider_name' 为外部数据源的 OLE DB 提供程序名称,'init_string' 为连接字符串,'external_table' 为外部数据源的表名或查询语句。这样,就可以将外部数据源的数据查询到 SQL Server 中。
如果要使用 OPENROWSET 函数将 SQL Server 中的数据导出到外部数据源中,可以使用以下语法:
```
INSERT INTO OPENROWSET('provider_name', 'init_string', 'SELECT * FROM external_table')
SELECT * FROM local_table
```
其中,'provider_name' 为外部数据源的 OLE DB 提供程序名称,'init_string' 为连接字符串,'external_table' 为外部数据源的表名或查询语句,local_table 为 SQL Server 中的表名。这样,就可以将 SQL Server 中的数据导出到外部数据源中。
需要注意的是,使用 OPENROWSET 函数需要在 SQL Server 中启用 Ad Hoc 分布式查询,否则会出现以下错误:
```
Msg 15281, Level 16, State 1, Line 1
SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure.
```
要启用 Ad Hoc 分布式查询,可以使用以下命令:
```
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
```
启用后,可以使用 OPENROWSET 函数查询、导入、导出外部数据源的数据。