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)
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With