简体   繁体   中英

OpenRowset with dynamic sql variable insert query

I want to execute this query. Because only OPENROWSET don't work with variable :

EXEC
 (
 '
 Insert into Table1 
 SELECT *
From OPENROWSET(MICROSOFT.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\Users\AA\Desktop\Table1.xlsx',
'SELECT *
 FROM [Sheet1$] ) '
)

For insert in a table on SQL Server 2008 with a variable SQL. My objectif is to make the filepath dynamic like database='+@FilePath+'

Finally using this code in ado.Net in openFiledialog control

But it doesn't work I get a syntax error

I have solved but without insert query I think the same thing with insert always escape the quotes like that

EXEC
 (
'SELECT *
From OPENROWSET(''MICROSOFT.ACE.OLEDB.12.0'',
''Excel 12.0;Database=C:\Users\AA\Desktop\Table1.xlsx'',
''SELECT *
 FROM [Sheet1$]'') T
 ')

and with FilePath :

Declare 
@FilePath nvarchar(50)
SET @FilePath='C:\Users\AA\Desktop\Table1.xlsx'
 EXEC
 (
'SELECT *
From OPENROWSET(''MICROSOFT.ACE.OLEDB.12.0'',
''Excel 12.0;Database='+@FilePath+''',
''SELECT *
 FROM [Sheet1$]'') T
 ')

Your need to use dynamic sql for this And also it best to explicitly use Column Names in your INSERT INTO and SELECT statements. you can do something as follows.

DECLARE @SheetName NVARCHAR(MAX);
DECLARE @FilePath  NVARCHAR(MAX);
DECLARE @Sql       NVARCHAR(MAX);

SET @Sql =  N' INSERT INTO Table1 '                            +
            N' SELECT *  '                                     +
            N' FROM OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ' +
            N' ''Excel 8.0;Database='+ @FilePath + ';'' ,'     +
            N' ''SELECT* FROM ['+ @SheetName +']'')' 

EXECUTE sp_executesql @Sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM