Importing data from Excel through stored procedure

无人久伴 提交于 2019-12-08 03:56:18

问题


I would like to enter my table name with the SP, so that it imports the data from excel sheet and loads onto database. But, receiving the following error. Can you please correct it. Thank you.

create proc Up_Export 
(
@Tablename as varchar(20) = null
)
AS
SET NOCOUNT ON
begin
INSERT INTO @Tablename --Receiving error over here, informs incorrect syntax near @tablename
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=C:\..\..\..\packages\@Tablename.xls', @Tablename)
set nocount off
end

回答1:


I see two things that aren't right.

First you do

INSERT INTO @Tablename 

You cannot use a variable at that place. Instead you should use dynamic sql like this

exec
('
INSERT INTO ' + @Tablename + ' SELECT * FROM OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', 
''Excel 8.0;Database=C:\..\..\..\packages\@Tablename.xls'', ''select * from myTable'')
')

Note that you have to use double single quotes like '' inside of the string. "Escaping" the single quote is needed because if you didn't it would signal the end of the string.

The second thing which does not seem right is the second argument where where you put @Tablename

'Excel 8.0;Database=C:\..\..\..\packages\@Tablename.xls', @Tablename)

You should have something like the following as your second argument

'SELECT * FROM [Sheet2$]'

Where Sheet2 is the sheet in your excel

Try some variations and pay attention to the feedback the sql parser gives you in case of error. Good luck!



来源:https://stackoverflow.com/questions/10690176/importing-data-from-excel-through-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!