Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats wrong with this SQL statement for table variable bulk insert

I'm trying to insert a CSV into a Temporary table and this SQL statement doesn't seem to work.

DECLARE @TempTable TABLE (FName nvarchar(max),SName nvarchar(max),
                          Email nvarchar(max));
BULK INSERT @TempTable 
FROM 'C:\52BB30AD694A62A03E.csv' 
WITH (FIELDTERMINATOR = ',',ROWTERMINATOR = '\n')

Getting the following error....

Incorrect syntax near '@TempTable'.

like image 787
chris Avatar asked Jan 01 '13 20:01

chris


People also ask

How does SQL bulk insert work?

BULK INSERT loads data from a data file into a table. This functionality is similar to that provided by the in option of the bcp command; however, the data file is read by the SQL Server process. For a description of the BULK INSERT syntax, see BULK INSERT (Transact-SQL).

Is bulk insert a single transaction?

The bulk insert operation is broken into batches, each batch is treated in its own transaction so the whole operation isn't treated under a single transaction.

Does bulk insert lock table?

Why does bulk insert lock the entire table? Specifies that a table-level lock is acquired for the duration of the bulk-import operation. A table can be loaded concurrently by multiple clients if the table has no indexes and TABLOCK is specified.


1 Answers

You cannot BULK INSERT into a table variable. So this line:

BULK INSERT @TempTable 

Is what is causing the error.


FYI, the simplest fix for this is probably just to use a #Temp table instead of a Table Variable. So your SQL code would change to this:

CREATE TABLE #TempTable (FName nvarchar(max),SName nvarchar(max),
                          Email nvarchar(max));
BULK INSERT #TempTable 
FROM 'C:\52BB30AD694A62A03E.csv' 
WITH (FIELDTERMINATOR = ',',ROWTERMINATOR = '\n')
like image 77
RBarryYoung Avatar answered Oct 21 '22 18:10

RBarryYoung