5

I'm trying to create a stored procedure to import from CSV. Everything works if I have a hard coded file path, but I want to take a file path as a parameter. When I try SQL Sever Management Studio generates an error:

Incorrect syntax near '@filePath'.

(In fact, if I put anything but a pure string(eg. 'C:'+'/dir') it gives an error.)

This is a simplified version of my code:

Create procedure [importFile](@filePath varchar(Max))
AS
BEGIN
    create table #Temp
    (
      row1 int,
      row2 varchar(5),
      row3 bit
    )
    BULK insert
      #Temp
      from @filePath
      With(
        FIELDTERMINATOR = ',',
        ROWTERMINATOR = '\n'
      )
    ...
END

Any explanation?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MegaTom
  • 312
  • 1
  • 6
  • 14
  • 3
    Plain and simple: `BULK INSERT` doesn't **support** parameters - you **have to** use hard-coded string - or resort to dynamic SQL to build up the SQL statement as a string and then execute it – marc_s Oct 24 '14 at 21:08
  • Does this answer your question? [How to cast variables in T-SQL for bulk insert?](https://stackoverflow.com/questions/5019041/how-to-cast-variables-in-t-sql-for-bulk-insert) – wibeasley Aug 07 '20 at 22:43

1 Answers1

7

Use dynamic SQL to inject the file name variable into a string with the bulk insert statement and the use sp_executesqlto execute it. You might want to add some error checking to check that the path is valid and so on.

CREATE PROCEDURE [importFile] (@filePath VARCHAR(MAX))
AS
BEGIN
    CREATE TABLE #Temp
    (
      row1 int,
      row2 varchar(5),
      row3 bit
    )

    DECLARE @SQL NVARCHAR(MAX) = ''
    SET @SQL = N'
    BULK INSERT #Temp
      FROM ''' + @filePath + '''
      WITH (
        FIELDTERMINATOR = '','',
        ROWTERMINATOR = ''\n''
      )'

     -- ...

     EXEC sp_executesql @SQL
END

-- to run it:
EXEC importFile 'd:\test.csv'
jpw
  • 44,361
  • 6
  • 66
  • 86