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?

Zack Stone
  • 643
  • 2
  • 10
  • 23

2 Answers2

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.

S3S
  • 24,809
  • 5
  • 26
  • 45
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);
Dan Guzman
  • 43,250
  • 3
  • 46
  • 71