0

I trying to insert data from a database into multiple reports. I would like to made the destination file name to be dynamic, which was a variable. But when I replace the file name with variable, I get a syntax error.

insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0', 
'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;',
'SELECT * FROM [Sheet1$]')
    select * from myresult;

enter image description here

What would be the easy way to fix this?

1
  • 2
    Be aware the T-SQL is a very crufty language. If the syntax diagram only shows a literal string as a possibility, that usually means that only a literal string is allowed. Not variables. Not expressions. Indeed, the remarks lower on that page state it doesn't accept variables. Commented Dec 8, 2017 at 6:50

1 Answer 1

1

Use a dynamic query

DECLARE @value NVARCHAR(MAX)
SET @value = 'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;'

DECLARE @a NVARCHAR(MAX)
SET @a = 'insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', 
''' + @value + ''',
''SELECT * FROM [Sheet1$]'')
    select * from myresult;'

PRINT @a
EXEC @a

Print @a result:

    insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0', 
    'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;',
    'SELECT * FROM [Sheet1$]')
     select * from myresult;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.