33

i am trying to bulk insert into Db using sql server 2005

Below is the code.

declare @path varchar(500) 
set @path = 'E:\Support\test.csv'; 

Create table #mytable( name varchar(max), class varchar(max), roll varchar(max) )

BULK INSERT #mytable FROM @path <-- Error line
WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ); 
Go 
select * from #mytable
drop table #mytable

Problem: issue is that my file path is dynamic and comes from a variable instead of hard coding which is not working If i change the error line to below it works

 BULK INSERT #mytable FROM 'E:\Support\test.csv'; 

Please advise how to fix this

Pondlife
  • 15,573
  • 6
  • 35
  • 51
Amit
  • 6,571
  • 21
  • 51
  • 88
  • 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:41

2 Answers2

43

Try to use Dynamic SQL:

declare @sql varchar(max)
set @sql = 'BULK INSERT #mytable FROM ''' + @path + ''' WITH ...
exec (@sql)
Peter
  • 35,292
  • 38
  • 140
  • 191
Andomar
  • 225,110
  • 44
  • 364
  • 390
  • 3
    For future users, notice that there are 3 quotes before/after the variable. It took me a while to make it work because I was only adding 2 – Berni Mar 26 '14 at 21:26
10
DECLARE @path varchar(50) = 'D:\ARQUIVOS_CARGAS\CABOS\FILE.prn'
DECLARE @SQL_BULK VARCHAR(MAX)
SET @SQL_BULK = 'BULK INSERT #TAB FROM ''' + @path + ''' WITH
        (
        CODEPAGE = ''ACP'',
        FIRSTROW = 1,
        FIELDTERMINATOR = ''tab'',
        ROWTERMINATOR = ''0x0a'',
        KEEPNULLS
        )'

EXEC (@SQL_BULK)
Taryn
  • 234,956
  • 54
  • 359
  • 399
Philip
  • 117
  • 2
  • 6