2

I am trying to import a csv file dynamically.

This works:

BULK
INSERT #CSV
FROM 'C:\Users\MyName\Desktop\Players.csv'
WITH
(
 FIELDTERMINATOR = ',',
 ROWTERMINATOR = '\n'
)

I would like to change it to be with a @path parameter like that:

DECLARE @path NVARCHAR(4000) = 'C:\Users\MyName\Desktop\Players.csv';
BULK
INSERT #CSV
FROM @path
WITH
(
 FIELDTERMINATOR = ',',
 ROWTERMINATOR = '\n'
)

But this does not compiles.

How could I do that?

Thanks in advance.

asked Nov 23, 2014 at 20:49

1 Answer 1

3

You would need to use Dynamic SQL to pass a dynamic file path to the Bulk Insert.

DECLARE @FileName NVARCHAR(4000);
SET @FileName = '/path/to.csv';
DECLARE @sql NVARCHAR(4000) = 'BULK INSERT #CSV 
 FROM ''' + @FileName + ''' WITH ( FIELDTERMINATOR ='','', ROWTERMINATOR =''\n'' )';
EXEC(@sql);
answered Nov 23, 2014 at 21:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.