I need a stored procedure that will do a bulk insert for multiple .csv files into tables in SQL Server. The .csv files all sit in a folder. The .csv files are tab delimited. I am able to iterate through the folder and create a record in a table named FileNames with each file in it. I get an error when it gets to the BULK INSERT code.
It's an incorrect syntax error near '-'. BULK INSERT FILE01-K FROM C:\Temp\CSV_FILES\FILE01-K.csv')
My procedure:
declare @filename varchar(255),
@path varchar(255),
@sql varchar(8000),
@cmd varchar(1000)
--get the list of files to process
SET @path = 'C:\Temp\CSV_FILES\'
SET @cmd = 'dir ' + @path + '*.csv /b'
--clear the FileNames table
DELETE FROM FileNames
INSERT INTO FileName(FileName)
EXEC Master..xp_cmdShell @cmd
UPDATE FileName SET FilePath = @path where FilePath is null
DELETE FROM FileNames WHERE FileName is null
--cursor loop
declare c1 cursor for SELECT FilePath,FileName FROM FileNames where FileName like '%.csv%' order by FileName desc
open c1
fetch next from c1 into @path,@filename
While @@fetch_status <> -1
begin
set @sql = 'BULK INSERT '+ Replace(@filename, '.csv','')+' FROM '+@Path+@filename+''')'
print @sql
exec (@sql)
fetch next from c1 into @path,@filename
end
close c1
deallocate c1
I've searched and found some examples, including up here that I've used to try and build mine.