如何使用SQL Server链接服务器查询Excel数据

Linked servers allow SQL Server access to data from a remote data source. A remote data source can be another SQL Server instance or other data sources such MySQL, Access databases, Oracle, Excel workbooks, text files etc.

链接服务器允许SQL Server从远程数据源访问数据。 远程数据源可以是另一个SQL Server实例,也可以是其他数据源,例如MySQL,Access数据库,Oracle,Excel工作簿,文本文件等。

SQL Server connects to the remote data source via an OLE DB provider. There are variations of the OLE DB providers depending on data source that want to establish connection to. There are the Microsoft OLE DB Provider for Oracle, Microsoft OLE DB Provider for SQL Server, OLE DB Provider for Jet etc. providers:

SQL Server通过OLE DB提供程序连接到远程数据源。 OLE DB提供程序有所不同,具体取决于要建立连接的数据源。 有用于Oracle的 Microsoft OLE DB提供程序,用于SQL Server的Microsoft OLE DB提供 程序,用于Jet的OLE DB提供程序等提供程序:

Microsoft SQL Server supports connections to other OLE DB data sources on a persistent or an ad hoc basis. The persistent connection is known as a linked server. An ad hoc connection, that is made for the sake of a single query, is known as a distributed query.

Microsoft SQL Server支持持久地或临时地连接到其他OLE DB数据源。 持久连接称为链接服务器。 为进行单个查询而建立的临时连接称为分布式查询。

A distributed query can be run without creating a linked server first, by using the Transact-SQL OPENROWSET and OPENDATASOURCE functions.

通过使用Transact-SQL OPENROWSETOPENDATASOURCE函数,可以运行分布式查询而无需先创建链接服务器。

When executing a T-SQL statement against a linked server, the OLE DB provider (e.g. OLE DB Provider for Jet) for the linked server is loaded into the SQL Server memory address space, then SQL Server takes the T-SQL statement and calls the OLE DB interface. Then the OLE DB interface provides a connection to the remote data source (e.g. Excel file). The OLE DB provider then processes the result set and returns the results to the SQL Server client that made the initial call.

当对链接服务器执行T-SQL语句时,将链接服务器的OLE DB提供程序(例如Jet的OLE DB提供程序 )加载到SQL Server内存地址空间中,然后SQL Server接收T-SQL语句并调用OLE DB接口。 然后,OLE DB接口提供到远程数据源(例如Excel文件)的连接。 OLE DB提供程序然后处理结果集,并将结果返回给进行初始调用SQL Server客户端。

In this article we’ll show how to create a linked server to query Excel data from the Excel file (*.xlsx) using the Microsoft.ACE.OLEDB.12.0 OLE DB provider and also how can be done by using the OPENROWSET and OPENDATASOURCE functions.

在本文中,我们将展示如何使用Microsoft.ACE.OLEDB.12.0 OLE DB提供程序创建链接服务器以从Excel文件(* .xlsx)查询Excel数据,以及如何使用OPENROWSETOPENDATASOURCE进行操作功能。

使用Microsoft.ACE.OLEDB.12.0 OLE DB提供程序创建链接的服务器 (Creating a linked server with the Microsoft.ACE.OLEDB.12.0 OLE DB provider)

To import data from an Excel file (Excel 2007 (xlsx) and above) to SQL Server the Microsoft.ACE.OLEDB.12.0 OLE DB driver should be installed.

要将数据从Excel文件(Excel 2007(xlsx)及更高版本)导入SQL Server,应安装Microsoft.ACE.OLEDB.12.0 OLE DB驱动程序。

The Microsoft.ACE.OLEDB.12.0 OLE DB driver can be used on SQL Server 32-bit editions for Excel 2007 files, or later, or on SQL Server 64-bit editions for any Excel files.

Microsoft.ACE.OLEDB.12.0 OLE DB驱动程序可以在Excel 2007文件或更高版本SQL Server 32位版本上使用,或者在任何Excel文件SQL Server 64位版本上使用。

There is one more provider; Microsoft. Jet. OLEDB.4.0 which can be used on SQL Server 32-bit editions for Excel 2003 files (or earlier).

还有一个提供者; 微软。 喷射。 OLEDB.4.0可以在SQL Server 32位版本的Excel 2003文件(或更早版本)上使用。

A list of all currently available providers in SQL Server can be seen under the Providers folder:

可以在Providers文件夹下看到SQL Server中所有当前可用的提供程序的列表:

From this link you can download and install the Microsoft.ACE.OLEDB.12.0 OLE DB driver. Depending on which version of SQL Server (32-bit or 64-bit) use, there are two versions of the Microsoft.ACE.OLEDB.12.0 OLE DB driver that can be installed:

从此链接,您可以下载并安装Microsoft.ACE.OLEDB.12.0 OLE DB驱动程序。 根据使用哪个版本SQL Server(32位或64位),可以安装两个版本的Microsoft.ACE.OLEDB.12.0 OLE DB驱动程序:

  • AccessDatabaseEngine.exe is for the SQL Server 32-bit version AccessDatabaseEngine.exe适用于SQL Server 32位版本
  • AccessDatabaseEngine_X64.exe is for the SQL Server 64-bit version AccessDatabaseEngine_X64.exe适用于SQL Server 64位版本

Note that if AccessDatabaseEngine_X64.exe was installed, and SQL Server 32-bit version is used. The error below may appear when creating a linked server for querying Excel data:

请注意 ,如果安装了AccessDatabaseEngine_X64.exe ,并且使用的是SQL Server 32位版本。 创建用于查询Excel数据的链接服务器时,可能会出现以下错误:

Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
– – – – – – – – – – – – – – – –
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
– – – – – – – – – – – – – – – –
The OLE DB provider “Microsoft.ACE.OLEDB.12.0” has not been registered. (Microsoft SQL Server, Error: 7403)

无法检索此请求的数据。 (Microsoft.SqlServer.Management.Sdk.Sfc)
– – – – – – – – – – – – – – – –
附加信息:
执行Transact-SQL语句或批处理时发生异常。 (Microsoft.SqlServer.ConnectionInfo)
– – – – – – – – – – – – – – – –
OLE DB提供程序“ Microsoft.ACE.OLEDB.12.0”尚未注册。 (Microsoft SQL Server,错误:7403)

When the appropriate AccessDatabaseEngine executable file is installed, the Microsoft.ACE.OLEDB.12.0 OLE DB driver will appear in the list of the available drivers under the Providers folder:

安装适当的AccessDatabaseEngine可执行文件后, Microsoft.ACE.OLEDB.12.0 OLE DB驱动程序将出现在Providers文件夹下的可用驱动程序列表中:

After installing appropriate AccessDatabaseEngine, a linked server can be created. To do that, right click on the Linked Servers folder and choose the New Linked Server command:

安装适当的AccessDatabaseEngine之后,可以创建链接服务器。 为此,请右键单击“ 链接服务器”文件夹,然后选择“ 新建链接服务器”命令:

This will open the New Linked Server dialog:

这将打开“ 新建链接服务器”对话框:

In this dialog, the name of a linked server and server type must be identified. In the Linked server box any name for the linked server can be entered (e.g. ExcelData).

在此对话框中,必须标识链接服务器的名称和服务器类型。 在链接服务器框中,可以输入链接服务器的任何名称(例如ExcelData)。

If SQL Server is checked, then a linked server will be an SQL Server instance. More about creating a SQL Server linked server can be found on the How to create and configure a linked server in SQL Server Management Studio page. Since this article is about using the Excel data source, in the Server type section, choose the Other data source radio button and from the Providers combo box, choose the Microsoft Office 12.0 Access Database Engine OLE DB Provider item:

如果选中了SQL Server ,则链接服务器将是SQL Server实例。 有关如何创建和配置 SQL Server链接服务器的更多信息,请参见如何在SQL Server Management Studio中创建和配置链接服务器 。 由于本文是关于使用Excel数据源的,因此在“ 服务器类型”部分中,选择“ 其他数据源”单选按钮,然后从“ 提供者”组合框中选择“ Microsoft Office 12.0 Access数据库引擎OLE DB提供程序”项:

In the Product name box, put the name of the OLE DB data source to add as a linked server (e.g. Excel). In the Data source box the type the full path and file name of the Excel file (e.g. C:\Test\Excel_Data.xlsx).

在“ 产品名称”框中,输入要添加为链接服务器(例如Excel)的OLE DB数据源的名称。 在“ 数据源”框中,键入Excel文件的完整路径和文件名(例如C:\ Test \ Excel_Data.xlsx)。

For the Provider string field, enter Excel 12.0:

提供者字符串字段中,输入Excel 12.0

Note, if you are using the Excel 97-2003 (.xls) files, in the Provider string field should be enter “Excel 8.0”.

注意,如果您使用的是Excel 97-2003(.xls)文件,则在提供程序字符串字段中应输入“ Excel 8.0”

In case that the wrong name was entered in the Provider string field, the following error will appear:

如果在提供者字符串字段中输入了错误的名称,则会出现以下错误:

The linked server has been created but failed a connection test. Do you want to keep the linked server?
– – – – – – – – – – – – – – – –
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
– – – – – – – – – – – – – – – –
Cannot initialize the data source object of OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “EXCELDATA”.
OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “EXCELDATA” returned message “Could not find installable ISAM.”. (Microsoft SQL Server, Error: 7303)

链接服务器已创建,但连接测试失败。 您要保留链接服务器吗?
– – – – – – – – – – – – – – – –
附加信息:
执行Transact-SQL语句或批处理时发生异常。 (Microsoft.SqlServer.ConnectionInfo)
– – – – – – – – – – – – – – – –
无法初始化链接服务器“ EXCELDATA”的OLE DB提供程序“ Microsoft.ACE.OLEDB.12.0”的数据源对象。
链接服务器“ EXCELDATA”的OLE DB提供程序“ Microsoft.ACE.OLEDB.12.0”返回消息“找不到可安装的ISAM。”。 (Microsoft SQL Server,错误:7303)

After entering the correct name in the Provider string field, press the OK button on the New Linked Server dialog to create the new linked server. During the process of creating a linked server the below error message may appear:

在“ 提供程序字符串”字段中输入正确的名称后,按“新建链接服务器”对话框上的“ 确定”按钮以创建新的链接服务器。 在创建链接服务器的过程中,可能会出现以下错误消息:

Press Yes to create the EXCELDATA linked server. The EXCELDATA linked server will appear under the Linked Server folder:

按“ 是”创建EXCELDATA链接服务器。 EXCELDATA链接服务器将出现在“ 链接服务器”文件夹下:

But when you look for data in the Tables folder of the default database the following error will appear:

但是,当您在默认数据库的Tables文件夹中查找数据时,将出现以下错误:

Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
– – – – – – – – – – – – – – – –
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
– – – – – – – – – – – – – – – –
Cannot initialize the data source object of OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “EXCELDATA”. (Microsoft SQL Server, Error: 7303)

无法检索此请求的数据。 (Microsoft.SqlServer.Management.Sdk.Sfc)
– – – – – – – – – – – – – – – –
附加信息:
执行Transact-SQL语句或批处理时发生异常。 (Microsoft.SqlServer.ConnectionInfo)
– – – – – – – – – – – – – – – –
无法初始化链接服务器“ EXCELDATA”的OLE DB提供程序“ Microsoft.ACE.OLEDB.12.0”的数据源对象。 (Microsoft SQL Server,错误:7303)

To resolve this error and the error above, close SQL Server Management Studio (SSMS) and run it again, but this time as an administrator:

要解决此错误和以上错误,请关闭SQL Server Management Studio(SSMS)并再次运行,但是这次以管理员身份运行:

Now, when expanding the Tables folder, the Excel sheets will appear. Note that every sheet is shown as SQL Server table with a dollar sign ($) at the end:

现在,展开“ 表”文件夹时,将出现Excel工作表。 请注意,每个工作表都显示为SQL Server表,末尾带有一个美元符号($):

To create the a linked server by using T-SQL simply use the sp_addlinkedserver stored procedure paste and execute the following code into a query editor:

要使用T-SQL创建链接服务器,只需使用sp_addlinkedserver存储过程粘贴并在查询编辑器中执行以下代码:

 
EXEC sp_addlinkedserver
     @server = N'EXCELDATA',
     @srvproduct = N'Excel',
     @provider = N'Microsoft.ACE.OLEDB.12.0',
     @datasrc = N'C:\Test\Excel_Data.xlsx',
     @provstr = N'Excel 12.0';
 

More about creating a linked server using T-SQL can be found on the How to create, configure and drop a SQL Server linked server using Transact-SQL page.

有关如何使用T-SQL创建链接服务器的更多信息,请参见如何使用Transact-SQL创建,配置和删除SQL Server链接服务器页面。

使用链接服务器查询Excel数据 (Querying Excel data using the linked server)

Now that the linked server is created, let’s query some Excel data!

现在已创建链接服务器,让我们查询一些Excel数据!

The following SQL code will list all data from the Sheet1 in the Excel_Data.xlsx file for which we are created the linked server:

以下SQL代码将列出我们为其创建链接服务器的Excel_Data.xlsx文件中Sheet1中的所有数据:

 
SELECT * FROM EXCELDATA...[Sheet1$]
 

But, when execute this code the error message may appear:

但是,执行此代码时,可能会出现错误消息:

Msg 7399, Level 16, State 1, Line 2
The OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “EXCELDATA” reported an error. Access denied.
Msg 7301, Level 16, State 2, Line 2
Cannot obtain the required interface (“IID_IDBCreateCommand”) from OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “EXCELDATA”.

消息7399,第16层,状态1,第2行
链接服务器“ EXCELDATA”的OLE DB提供程序“ Microsoft.ACE.OLEDB.12.0”报告了一个错误。 拒绝访问。
消息7301,第16级,州2,第2行
无法从OLE DB提供程序“ Microsoft.ACE.OLEDB.12.0”获得链接服务器“ EXCELDATA”的所需接口(“ IID_IDBCreateCommand”)。

This usually happens because of inadequate permissions.

这通常是由于权限不足而发生的。

One way to resolve this is, go to the SQL Server Configuration Manager:

解决此问题的一种方法是,转到SQL Server配置管理器:

From the SQL Server Configuration Manager dialog, select SQL Server for on which has created a linked server:

在“ SQL Server配置管理器”对话框中,选择为其创建了链接服务器SQL Server:

Right click, and from the context menu, click the Properties option:

右键单击,然后从上下文菜单中单击“ 属性”选项:

On the SQL Server Properties dialog under the Log on cart, choose the Built-in account radio button and from the combo box, select the Local System item:

在“ 登录购物车”下的“ SQL Server属性”对话框 ,选择“ 内置帐户”单选按钮,然后从组合框中选择“ 本地系统”项:

From the SQL Server Properties dialog click the Apply button and press the Yes button on the Confirm Account Change warning message box:

在“ SQL Server属性”对话框中,单击“ 应用”按钮,然后在“确认帐户更改”警告消息框上按“ 是”按钮:

Now, open SQL Server Manage Studio as administrator and in a query editor execute the SQL code:

现在,以管理员身份打开SQL Server Manage Studio,并在查询编辑器中执行SQL代码:

 
SELECT * FROM EXCELDATA...Sheet1$
 

The following result will appear:

将显示以下结果:

This will list all data from Sheet1 of the Excel_Data.xlsx file.

这将列出Excel_Data.xlsx文件的Sheet1中的所有数据。

After all these settings, you are still getting the same error, maybe Microsoft Data Access Components (MDAC) do not be work properly. For more information, see this Microsoft article.

完成所有这些设置后,您仍然会遇到相同的错误,也许Microsoft数据访问组件(MDAC)无法正常工作。 有关更多信息,请参见这篇Microsoft文章

The following SQL code will insert data from Sheet1 to the SQL Server table ‘SQLTable’:

以下SQL代码会将数据从Sheet1插入到SQL Server表“ SQLTable”中:

 
INSERT INTO dbo.SQLTable(ID,Name)
SELECT ID, Name FROM EXCELDATA...Sheet1$
 

When query the SQLTable table, the following result will appear:

查询SQLTable表时,将显示以下结果:

使用分布式查询查询Excel数据 (Querying Excel data using the distributed queries)

To access data to an Excel file via SSMS without creating a linked server first use the Transact-SQL OPENROWSET and OPENDATASOURCE functions.

要通过SSMS访问Excel文件中的数据而不创建链接服务器,请首先使用Transact-SQL OPENROWSETOPENDATASOURCE函数。

To establish connection and querying data from the Excel data source using OPENROWSET function type the following SQL code in query editor:

要使用OPENROWSET函数从Excel数据源建立连接和查询数据,请在查询编辑器中键入以下SQL代码:

 
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Test\Excel_Data.xlsx;', 'SELECT * FROM [Sheet1$]')
 

But, when executing the above code the following error may occur:

但是,执行上述代码时,可能会发生以下错误:

Msg 15281, Level 16, State 1, Line 8
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. For more information about enabling ‘Ad Hoc Distributed Queries’, search for ‘Ad Hoc Distributed Queries’ in SQL Server Books Online.

Msg 15281,第16级,状态1,第8行
SQL Server阻止访问组件“临时分布式查询”的STATEMENT“ OpenRowset / OpenDatasource”,因为此服务器的安全配置已将此组件关闭。 系统管理员可以使用sp_configure启用“临时分布式查询”的使用。 有关启用“临时分布式查询”的更多信息,请在SQL Server联机丛书中搜索“临时分布式查询”。

To resolve this error the Ad Hoc Distributed Queries option should be enabled in order to open a connection to a remote server using the OPENROWSET or OPENDATASOURCE. This can be achieved by using the sp_configure procedure and execute the following SQL code in a query editor:

要解决此错误,应启用“ 临时分布式查询”选项,以便使用OPENROWSETOPENDATASOURCE打开到远程服务器的连接。 这可以通过使用sp_configure过程并在查询编辑器中执行以下SQL代码来实现:

 
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
 

If case that the above executed query show the following error:

如果上述执行的查询显示以下错误:

Configuration option ‘show advanced options’ changed from 0 to 1. Run the RECONFIGURE statement to install.
Msg 5808, Level 16, State 1, Line 2
Ad hoc update to system catalogs is not supported.

配置选项“显示高级选项”从0更改为1。运行RECONFIGURE语句进行安装。
消息5808,第16级,状态1,第2行
不支持对系统目录的临时更新。

Use the RECONFIGURE WITH OVERRIDE instead of RECONFIGURE:

使用RECONFIGURE WITH OVERRIDE而不是RECONFIGURE

 
EXEC sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE WITH OVERRIDE
 

Now when executing the SQL code:

现在,当执行SQL代码时:

 
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Test\Excel_Data.xlsx;', 'SELECT * FROM [Sheet1$]')
 

The following result in the Results grid will be shown:

结果网格中将显示以下结果:

The same result can be obtained used the OPENDATASOURCE function. Type the following code:

使用OPENDATASOURCE函数可以获得相同的结果。 输入以下代码:

 
SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
  'Data Source=C:\Test\Excel_Data.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]
 

Like linked servers, OPENROWSET and OPENDATASOURCE use OLE DB to connect to the remote data source; however, these functions do not encompass all the features included with linked servers, which is generally why linked servers are the preferred option.

像链接服务器一样,OPENROWSET和OPENDATASOURCE使用OLE DB连接到远程数据源。 但是,这些功能并未包含链接服务器随附的所有功能,这通常是为什么链接服务器是首选选项的原因。

Other articles in this series:

本系列的其他文章:

看更多 (See more)

To boost your SQL Server development productivity, check out Free SQL Server Management Studio add-ins.

为了提高您SQL Server开发效率,请查看Free SQL Server Management Studio加载项

有用的链接 (Useful links)

翻译自: https://www.sqlshack.com/query-excel-data-using-sql-server-linked-servers/

  • 0
    点赞
  • 0
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值