Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BULK INSERT with identity (auto-increment) column

I am trying to add bulk data in database from CSV file.

Employee table has a column ID (PK) auto-incremented.

CREATE TABLE [dbo].[Employee](  [id] [int] IDENTITY(1,1) NOT NULL,  [Name] [varchar](50) NULL,  [Address] [varchar](50) NULL ) ON [PRIMARY] 

I am using this query:

BULK INSERT Employee  FROM 'path\tempFile.csv '  WITH (FIRSTROW = 2,KEEPIDENTITY,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n'); 

.CSV File -

Name,Address name1,addr test 1 name2,addr test 2 

but it results in this error message:

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 2, column 1 (id).

like image 464
Abhi Avatar asked Jun 01 '12 13:06

Abhi


People also ask

How does Bulk insert command handle imported identity values?

Data files that contain identity values can be bulk imported into an instance of Microsoft SQL Server. By default, the values for the identity column in the data file that is imported are ignored and SQL Server assigns unique values automatically.

How do I add auto increment to a column?

Syntax for Access Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10,5) . VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table. The "Personid" column would be assigned a unique value.

How do you get the identity values in bulk copy in SQL?

just get the IDENTITY the same way you would if you inserted 1 record... the number of records is irrelevant? select them after they are inserted, you would need to include a bulk inserted identifier... so add column batchId or something and then re-select all records with the same batchid.

How can insert auto increment value in SQL query?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.


1 Answers

Add an id column to the csv file and leave it blank:

id,Name,Address ,name1,addr test 1 ,name2,addr test 2 

Remove KEEPIDENTITY keyword from query:

BULK INSERT Employee  FROM 'path\tempFile.csv '  WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n'); 

The id identity field will be auto-incremented.

If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.

like image 105
Josh Werts Avatar answered Sep 24 '22 18:09

Josh Werts