38

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
16.3k6 gold badges40 silver badges51 bronze badges
asked Apr 5, 2011 at 5:00
1

2 Answers 2

48

Try to use Dynamic SQL:

declare @sql varchar(max)
set @sql = 'BULK INSERT #mytable FROM ''' + @path + ''' WITH ...
exec (@sql)
Peter
38.8k39 gold badges151 silver badges211 bronze badges
answered Apr 5, 2011 at 5:07

2 Comments

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
Shoule be 'BULK INSERT #mytable FROM ' + QUOTENAME(@path, '''') + ' WITH ... to correctly escape the file name.
12
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
249k57 gold badges374 silver badges409 bronze badges
answered Dec 5, 2013 at 11:26

Comments

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.