I'm still fairly new to writing SQL scripts. I have a script which imports numerous excel files (possibly reaching 1000+). Some of these Excel spreadsheets have only one row and some have more than 50 rows. I'm importing all of these excel spreadsheets into one table and would like to be able to add a column which identifies which Excel spreadsheet, by filename, the record came from. So rows 1 through 10 may come from ExcelSpreadsheetA.xlsx and rows 11 through 15 may have come from ExcelSpreadsheetB.xlsx. Would I be able to set this identification up during the import process?
I use this script to perform my import from excel:
select *
into SQLServerTable
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
What I would like to do is add logic to the end of that script that says something like:
update sqlservertable
set filename = testing.xls
But I want it to set the filename attribute for just the records that had been imported from that specific filename. Ideally I would like the final table to look similar to the one below.
Col1 Col2 Col3 Filename
===== ===== ===== =========
1 A B export1.xlsx
2 C D export1.xlsx
3 E F export1.xlsx
4 G H export5.xlsx
5 I J export8.xlsx
6 K L export8.xlsx
@Pondlife This script does what I want it to do.
select *, 'file1.xls' as 'Filename'
into dbo.SQLServerTable
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [Sheet1$]')
However, now I need to be able to get a subsequent import into that same database, here is the script I'm using but it's erroring out on me.
INSERT INTO dbo.SQLServerTable
Select *, 'File2.xlsx' as 'FileName'
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\Convert\Converted\File2.xlsx;HDR=YES', 'SELECT * FROM [Worksheet$]')