Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk insert file path as stored procedure parameter

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?

like image 252
MegaTom Avatar asked Oct 24 '14 20:10

MegaTom


1 Answers

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'
like image 152
jpw Avatar answered Sep 29 '22 23:09

jpw