Importing data from Excel to SQL Server

Different ways to accomplish this are described in Microsoft KB article #321686. If importing is not recurring, or persistent connection is not possible, it makes sense to use Distributed Query. Running such query in SQL Server Management Studio of SQL Server 2005 will, however, produce the following error:

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', see "Surface Area Configuration" in SQL Server Books Online.

It can be resolved by enabling “advanced options” and “Ad Hoc distributed Queries” option, executing query to import data, and (optionally) reverting the configuration to its original state:

# First, enable advanced options
sp_configure ‘show advanced options’, 1
reconfigure
# Second, enable execution of Ad Hoc queries
sp_configure ‘Ad Hoc Distributed Queries’, 1
reconfigure
# Import data from Excel to SQL table
SELECT * INTO TableName FROM OPENROWSET(‘Microsoft.Jet.OLEDB.4.0’,
‘Excel 8.0;Database=Location\Name.xls’, [SheetName$])
# Revert both options back: first disable Ad Hoc distributed queries
sp_configure ‘Ad Hoc Distributed Queries’, 0
reconfigure
# … And hide advanced options
sp_configure ‘show advanced options’, 0
reconfigure
Importing data from Excel to SQL Server