I have two test transactions in two session respectively. Assuming these two transaction will run simultaneously. What I attempt to do is to let one transaction insert invoice number correctly after the other transaction is done. No duplicate. I did it as below. But if I remove with (tablockx) in session 2, they won't work any more. I checked on line book but no answer. Anybody would help? Serializable won't work since two SELECT want to be exclusive to each other here. Thanks.
In session 1:
begin transaction
declare @i int
select @i=MAX(InvNumber) from Invoice
with(tablockx)
where LocName='A'
waitfor delay '00:00:10'
set @i=@i+1
insert into Invoice values('A',@i);
commit
In session 2:
begin transaction
declare @i int
select @i=MAX(InvNumber) from Invoice
with(tablockx)
where LocName='A'
set @i=@i+1
insert into Invoice values('A',@i);
commit