Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an auto_increment key into SQL Server table

Tags:

sql

sql-server

I want to insert rows into a table that has a unique, non auto-incremented primary key.

Is there a native SQL function to evaluate the last key and increment it or do I have to do it in two steps:

key = select max(primary.key) + 1

INSERT INTO dbo.TABLE (primary.key, field1, fiels2) VALUES (KEY, value1, value2)
like image 768
Ruben Teixeira Avatar asked Dec 21 '12 17:12

Ruben Teixeira


2 Answers

Since it's auto-generated, simply don't provide it:

INSERT INTO bo.TABLE (field1, fiels2) VALUES (value1, value2)

Update: that will work if your column is an IDENTITY column.

To provide explicit values to an identity column, you have to do this:

set identity_insert bo.TABLE on

INSERT INTO bo.TABLE (primary_key, field1, fiels2) VALUES ((SELECT ISNULL(MAX(id) + 1, 0) FROM bo.Table), value1, value2)

set identity_insert bo.TABLE off

But there's no compelling reason for doing it this way.

like image 133
Jordão Avatar answered Sep 30 '22 22:09

Jordão


Judging by you comments throughout, you have a primary key on the table that is not an identity column.

If your version of SQL Server is SQL 2012 you should look into sequences: http://msdn.microsoft.com/en-us/library/ff878091.aspx

In other versions you either need to recreate the table using the IDENTITY property (http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx) for the primary key column or use a two step approach.

If you go with the two step approach you need to make sure that concurrently running inserts won't end up using the same new value. The easiest way to do that is this is by combining the select and the insert into one value and using the serializable table hint:

CREATE TABLE dbo.Tbl1(id INT PRIMARY KEY, val1 INT, val2 INT)

INSERT INTO dbo.Tbl1(id, val1, val2)
VALUES((SELECT ISNULL(MAX(id)+1,0) FROM dbo.Tbl1 WITH(SERIALIZABLE, UPDLOCK)), 42, 47);

SELECT * FROM dbo.Tbl1;
like image 25
Sebastian Meine Avatar answered Sep 30 '22 20:09

Sebastian Meine