Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BULK INSERT with variable file name

Tags:

sql

sql-server

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

like image 500
Amit Avatar asked Apr 05 '11 05:04

Amit


People also ask

How do you specify text qualifier in bulk insert?

You need to use a 'format file' to implement a text qualifier for bulk insert. Essentially, you will need to teach the bulk insert that there's potentially different delimiters in each field. Create a text file called "level_2. fmt" and save it.

Why bulk insert is faster than insert?

¶ Both 'Bulk insert with batch size' and 'Use single record insert' options are used for inserting records in a database table. The 'Bulk insert with batch size' option is used when you want the whole dataset to be loaded in batches of a specified size. Typically, larger batch sizes result in better transfer speeds.

What is codepage in bulk insert?

The CODEPAGE option is used when you need to load extended characters (values greater than 127); this option allows you to specify one of the following values for char, varchar, and text datatypes: ACP. Convert from the ANSI/Microsoft Windows code page (ISO 1252) to the SQL Server code page.


1 Answers

Try to use Dynamic SQL:

declare @sql varchar(max) set @sql = 'BULK INSERT #mytable FROM ''' + @path + ''' WITH ... exec (@sql) 
like image 188
Andomar Avatar answered Oct 04 '22 12:10

Andomar