I am using the below query to fetch the sales register excel data into a SQL Server table. Usually, the sheet name remains as 'Sales Register' but sometimes it changes to 'Sheet' or Some other names.
Currently, I have mentioned the static sheet name in my query. How I can pick a dynamic name so that even if my sheet name changes I shall be able to fetch the data without error.
Current scenario :
FROM [Sales Register$]'');'
I want it to be like:-
FROM [***ANY NAME*** $]'');'
Code:
SET @filePath1 = 'D:\.......\Sales_Register_'+ @curDate + '.xlsx'
SET @sql2 = 'INSERT INTO [MyDB].[dbo].[SalesRegister]
([Subsidairy],
[Date],
[Product],
[Quantity],
[Rate],
[Value])
SELECT
[Subsidairy],
[Date],
[Product],
[Quantity],
[Rate],
[Value]
FROM OPENROWSET
(''Microsoft.ACE.OLEDB.12.0'',''Excel 12.0;Database='+@filePath1+';
HDR=YES; IMEX=1'',
''SELECT
[Subsidairy],
[Date],
[Product],
[Quantity],
[Rate],
[Value]
FROM [Sales Register$]'');'
2条答案
按热度按时间jgwigjjp1#
You can use below code to get sheet_name from excel document.
After that you can write your code and use variable '@sheet_name' instead of '[Sales Register$]'.
p4rjhz4m2#
I needed to find all of the names of Excel tabs from a list of Excel files in a directory rather than just one worksheet.
I used value statements to insert my filenames into a temp table. The filename in this table had to have the full directory path included.
I used the answers in this thread to programmatically create that linked server and combined it with this cursor example answer to create my code:
https://stackoverflow.com/a/5856192
This was the code I came up with: