tags:

views:

71

answers:

3

I am using the following syntax to insert new records (I don't want to have duplicate keys):

insert into tbl(key) values select max(key)+1 from tbl

Someone says it will have concurrency problem.
Is that right?

SELECT -> LOCK table -> INSERT

or

LOCK table -> SELECT -> INSERT

Which one of the above is correct?

+1  A: 

If this happens inside a transaction you will be fine.

astander
is that true. Does a begin transaction block other begin transactions? Couldn't they both calculate max(key) as the same?
Lou Franco
If it's SERIALIZABLE then that's true, but I woudn't like to bet on it for any other isolation levels, especially CHAOS...
Greg Beech
A: 

The select will lock the table, and you are doing everything in a single statement, looks like you should be fine (other than maybe performance to calculate the max(key)).

Otávio Décio
Any reference link (e.g. msdn link) talking about this?
Billy
+1  A: 

If you're doing replication, your best bet is to use GUID's as a primary key and also "please" do not create clustered index on that column.

Mevdiven