concurrency - SQL Server Custom Identity Column -


i want generate custom identity column related type of product. can query guaranty order of identity , resolve concurrency. sample query:

 begin tran  insert tblkey values((select 'a-' + cast(max(cast(id int)) + 1 nvarchar) tblkey),'ehsan')  commit 

try this:

begin tran  insert tblkey values((select max(id) + 1 nvarchar) tblkey (updlock)),'ehsan')  commit 

when selecting max id acquire u lock on row. u lock incompatible u lock try acquire session same query running @ same time. 1 query executed @ given time. ids in order , continuous without gaps between them.

a better solution create table dedicated storing current or next id , use instead of maximum.

you can understand difference doing following:

prepare table

create table t(id int not null primary key clustered) insert t values(1) 

and run following query in 2 different sessions 1 after less 10 seconds apart

begin tran declare @idv int select @idv = max (id) t waitfor delay '0:0:10' insert t values(@idv+1) commit 

wait while until both queries complete. observe 1 of them succeeded , other failed.

now same following query

begin tran declare @idv int select @idv = max (id) t (updlock) waitfor delay '0:0:5' insert t values(@idv+1) commit 

view contents of t

cleanup t table drop table t


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -