Dizzle
Dizzle

Reputation: 1016

How to set SQL Server datatable insert and autoincrement column

I am using a DataTable and SqlBulkCopy to insert data into a SQL Server database table.

I have managed to bulk insert the rows using the following settings but only using negative values as otherwise I get conflicts as the value is not unique:

DataTable table = new DataTable();
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementSeed = 0;
column.AutoIncrementStep = -1;
table.Columns.Add(column);
table.Columns.Add(DB_Base.DBTable_Start, typeof(DateTime));

I have a loop that generates rows to be inserted like this:

table.Rows.Add(null,tsoOptions.start);

I then set the table and connection and write the data using the WriteToServer() method. This is all working fine and the rows appear but with negative autoincrement primary keys.

How do I modify this so that it will append the rows with a positive value which continues after the last (MAX) value without reading the max value in a separate query?

Upvotes: 0

Views: 2068

Answers (2)

Racil Hilan
Racil Hilan

Reputation: 25351

Assuming your table in the database is created properly with the column auto-increment (i.e. IDENTITY) turned on, don't duplicate this functionality in your code. Just send the records to the database with the null value for that column and the database will do its job. Comment out these lines and try:

//column.AutoIncrement = true;
//column.AutoIncrementSeed = 0;
//column.AutoIncrementStep = -1;

UPDATE Actually the best way to do it is by not mapping the identity column at all, so comment out all these lines:

//DataColumn column = new DataColumn();
//column.DataType = System.Type.GetType("System.Int32");
//column.AutoIncrement = true;
//column.AutoIncrementSeed = 0;
//column.AutoIncrementStep = -1;
//table.Columns.Add(column);
//table.Columns.Add(DB_Base.DBTable_Start, typeof(DateTime));

And make sure you're not using SqlBulkCopyOptions.KeepIdentity (check this).

Upvotes: 4

Hangarter
Hangarter

Reputation: 632

Do you need to setup this in the DataTable object? Usually I'd go on SSMS (Sql Server Management Studio) and set up the primary key as Identity and Increment to one. When I save in the database, I just don't send anything for this column:

1) Right-click on the table in SSMS tree on the left, choose design enter image description here

2) Click on your primary-key column and have a look on Column Properties section, you should set up like this: enter image description here

That should do the job!

UPDATE: Like the other guy here suggested, comment out the lines of your code that you are trying to set up seed and identity and do this in SSMS instead.

Upvotes: 0

Related Questions