SQL2005/SQL2008中使用SQL语句导入Excel的方法

注意此方法只能在SQL05以上版本才能使用,2000的请无视

格式如下:

insert into tableA
SELECT * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 8.0;IMEX=1;HDR=YES;DATABASE=D:\算神.xls',[sheet1$])

如果遇到下面的错误:

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.

 

请执行以下脚本:

exec sp_configure 'show advanced options',1 
reconfigure 
exec sp_configure 'Ad Hoc Distributed Queries',1 
reconfigure

PS:可以用VB/C#等编程语言拼凑此方法的SQL语句,然后使用SqlCommand执行,即可实现Excel的导入。不必像原来那样,先把Excel的值取出来,再循环插入SQL