0

I'm using dynamic SQL for bulk insert with a parameter (Bulk insert using stored procedure).

DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TblValues FROM ''' + @FileName + ''' WITH ( FIELDTERMINATOR ='','', ROWTERMINATOR =''\n'' )';
EXEC(@sql);

But... How to avoid SQL injection?

3
  • Take a look at sp_executesql learn.microsoft.com/en-us/sql/relational-databases/… Commented Aug 23, 2017 at 14:11
  • @Leonidas199x - sp_executesql works with parameters, and bulk insert doesn't support parameters in 'FROM' clause Commented Aug 23, 2017 at 14:13
  • My bad, wasn't aware of that. Commented Aug 23, 2017 at 14:21

2 Answers 2

1

You could use QUOTENAME to surround the file name in single quotes:

DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TblValues FROM ' + QUOTENAME(@FileName,'''') + ' WITH ( FIELDTERMINATOR ='','', ROWTERMINATOR =''\n'' )';
EXEC (@sql);
Sign up to request clarification or add additional context in comments.

Comments

1

One way would be to retrieve the file name versus pass it in... something like

DECLARE @fileLocation VARCHAR(128) = '\\some\folder\location'

IF OBJECT_ID('tempdb..#FileNames') IS NOT NULL DROP TABLE #FileNames
CREATE TABLE #FileNames(
    id int IDENTITY(1,1)
    ,subdirectory nvarchar(512)
    ,depth int
    ,isfile bit)
INSERT #FileNames(subdirectory,depth,isfile)
EXEC xp_dirtree @fileLocation, 1, 1

Then, in #FileNames will be all the files in that directory (where isfile = 1 of course). Then you can simply query the file name(s) from the temp table.

Comments

Your Answer

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.