Using openrowset to read an Excel file into a temp table; how do I reference that table?

时间秒杀一切 提交于 2019-12-24 00:58:08

问题


I'm trying to write a stored procedure that will read an Excel file into a temp table, then massage some of the data in that table, then insert selected rows from that table into a permanent table.

So, it starts like this:

SET @SQL = "select * into #mytemptable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database="+@file+";HDR=YES', 'SELECT * FROM [Sheet1$]')"

EXEC (@SQL)

That much seems to work.

However, if I then try something like this:

Select * from #mytemptable

I get an error:

Invalid object name '#mytemptable'

Why isn't #mytemptable recognized? Is there a way to have #mytemptable accessible to the rest of the stored procedure?

Many thanks in advance!


回答1:


I don't have time to mock this up, so I don't know if it'll work, but try calling your table '##mytemptable' instead of '#mytemptable'

I'm guessing your issue is that your table isn't in scope anymore after you exec() the sql string. Temp tables preceded with two pound symbols are globally accessible.

Don't forget to drop it when you're done with it!




回答2:


The way I've done this in the past was to: First, create the #temp_table using CREATE TABLE. Second, build the dynamic query as usual inserting into the #temp_table Third, use exec sp_executesql @sql.

With this method you won't need the globally scoped ##temp_table.




回答3:


You can use it in the same scope including the whole script in the dynamic query:

DECLARE @strSQL nvarchar(max)
DECLARE @file varchar(100)

SET @file='c:\myfile.xls'
SET @strSQL=N'SELECT * INTO #mytemptable FROM OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', ''Excel 8.0;Database='+@file+';HDR=YES'', ''SELECT * FROM [Sheet1$]'');'
SET @strSQL=@strSQL+N'SELECT * FROM #mytemptable'

EXECUTE sp_executesql @strSQL


来源:https://stackoverflow.com/questions/863735/using-openrowset-to-read-an-excel-file-into-a-temp-table-how-do-i-reference-tha

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