数据管理:Excel数据导入SQLServer

2013-10-06  籽藤 

跟同事S又学了一招导入Excel文件到SQL Server数据库的方法――通过T-SQL访问OLE DB数据源。
过去我只会用以下两种方法导入数据:
  1. 在SSMS(SQL Server Management Studio)中选择数据库,右键Task->Import Data;这其实是通过UI界面选择数据源进行导入
  2. 在CMD窗口中输入BCP命令进行数据导入

而我新学的方法呢,就是用如下语句进行导入;它会在当前数据中新建applwu_LoadMOBillingActivity的数据表,至于[p1$],附加美元符号 ($) 的 Excel 对象名称代表Excel文件中的工作表(例如:Sheet1$),而普通对象名称代表 Excel 指定的范围。

SELECT * INTO applwu_LoadMOBillingActivity FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=C:\Users\applewu\Desktop\LoadMOBillingActivity.xlsx', 'SELECT * FROM [p1$]')

Q&A

  • 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.

exec sp_configure 'show advanced options', 1;
RECONFIGURE;
exec sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

  • The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error

 有几种情况会导致这个错误:

    • Excel文件当前被打开了
    • 没有用Administrator打开SQL Server Management Studio
    • Excel绝对路径或当前用户访问文件的权限有问题。可用以下语句查看:

-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE;
GO

exec master..xp_cmdshell 'dir C:\Users\applewu\Desktop\LoadMOBillingActivity.xlsx'

MSDN上此类文章不少 http://support.microsoft.com/kb/321686 高效工作源自积累小技巧

362°/3628 人阅读/0 条评论 发表评论

登录 后发表评论