We have a folder of excel files that we want to import into our database using TSQL. We have the code to import the individual file using OpenRowSet, but need to find a way to loop through the files in the folder and run this code on each file. How can this be accomplished using TSQL?
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    11
            
            
         
    
    
        froadie
        
- 79,995
- 75
- 166
- 235
2 Answers
16
            
            
        Did some research, and found a way to loop over the files using something like this:
CREATE TABLE #tmp(excelFileName VARCHAR(100));
INSERT INTO #tmp
EXEC xp_cmdshell 'dir /B c:\my\folder\path\';
declare @fileName varchar(100)
While (Select Count(*) From #tmp where excelFileName is not null) > 0
Begin
    Select Top 1 @fileName = excelFileName From #tmp
    -- OPENROWSET processing goes here, using @fileName to identify which file to use
    Delete from #tmp Where excelFileName = @FileName
End
DROP TABLE #tmp
 
    
    
        froadie
        
- 79,995
- 75
- 166
- 235
- 
                    Add `/s` to the `dir` command so the query is independent of the current directory. – Neo Nov 28 '16 at 13:14
- 
                    Thanks for this script. It really helped me a lot. Cheers – Bat_Programmer May 21 '18 at 04:49
8
            
            
        Adding More to What Froadie said, you likely need to first enable use of the command shell (Enable 'xp_cmdshell' SQL Server) also your cmd shell path may need to have double quotes around it, This is an example that I got to work:
--Allow for SQL to use cmd shell
EXEC sp_configure 'show advanced options', 1    -- To allow advanced options to be changed.
RECONFIGURE -- To update the currently configured value for advanced options.
EXEC sp_configure 'xp_cmdshell', 1  -- To enable the feature.
RECONFIGURE -- To update the currently configured value for this feature.
--Loop through all of the files
CREATE TABLE #tmp(excelFileName VARCHAR(100));
INSERT INTO #tmp
EXEC xp_cmdshell 'dir /B "C:\_GENERAL RESOURCES\CANWET\ANUSPLINE DATA CONVERTER\AnusplineStationSelector\CCDP\Files\"';
declare @fileName varchar(100)
While (Select Count(*) From #tmp where excelFileName is not null) > 0
Begin
    Select Top 1 @fileName = excelFileName From #tmp
    PRINT(@filename)
    -- OPENROWSET processing goes here, using @fileName to identify which file to use
    Delete from #tmp Where excelFileName = @FileName
End
 
    