sql server - SQL unique field: concurrency bugs? -


this question has answer here:

i have db table field must unique. let's table called "table1" , unique field called "field1".

i plan on implementing performing select see if table1 records exist field1 = @valueforfield1, , updating or inserting if no such records exist.

the problem is, how know there isn't race condition here? if 2 users both click save on form writes table1 (at exact same time), , have identical values field1, isn't possible following happen?

user1 makes sql call, performs select operation , determines there no existing records field1 = @valueforfield1. user1's process preempted user2's process, finds no records field1 = @valueforfield1, , performs insert. user1's process allowed run again, , inserts second record field1 = @valueforfield1, violating requirement field1 unique.

how can prevent this? i'm told transactions atomic, why need table locks too? i've never used lock before , don't know whether or not need 1 in case. happens if process tries write locked table? block , try again?

i'm using ms sql 2008r2.

add unique constraint on field. way won't have select. have insert. first user succeed second fail.

on top of may make field autoincremented, won't have care on filling it, or may add default value, again not caring on filling it.

some options autoincremented int field, or unique identifier.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -