multithreading - Confused with MS SQL Server LOCK would help in INSERT Scenario.(Concurrency) -
business scenario: ticketing system, , got many user using application. when ticket(stored in 1st table in below) comes in application, user can hit ownership button , take ownershipf of it. 1 user can take ownership 1 ticket. if 2 user tries hit ownership button, first 1 wins , second gets incident or message no incident exists take ownership. here facing concurrency issue now. have lock implementation using table(2nd table in below).
i have 2 tables;
table(columns)
- ticket(ticketid-pk, owneruserid-fk)
- ticketownershiplock(ticketid-pk, owneruserid-fk, lockdate)note: here ticketid set primary key.
current lock implementation: whenever user 1 tries own ticket puts entry 2nd table ticketid, userid , current date,then goes update owneruserid in 1st table. before insert above said lock entry, procedure checks other user created lock same incident. if there lock, lock wont opened user. else lock entry wont entered , user cannot update ticket onwership. more info: there many tickets getting opened in 1st table, whenever user tries take ownership, should find next available ticket take ownership. need find ticket , calculation , set status ticket, there 1 more column in 1st table statusid. status assigned assigned.
problem: somehow 2 user's got ownership same ticket @ excatly same time, have checked millisecond same. 1. know if ms sql server lock in scenario. 2. or need block table while insert.(this 2nd rable not have data approx. less 15 rows)
lock creation procedure below:
alter procedure [dbo].[takeownershipgetlock] @ticketid [uniqueidentifier], @ownerid [uniqueidentifier] begin set nocount on; begin transaction takeownership begin try declare @lock bit set @lock = 0 declare @lockdate datetime select @lockdate = lockdate dbo.takeownershiplock ticketid = @ticketid if @lockdate null , not exists ( select 1 dbo.takeownershiplock takeownership (updlock) inner join dbo.ticket ticket (nolock) on ticket.ticketid = takeownership.ticketid takeownership.ticketid = @ticketid , ticket.ownerid null ) begin insert dbo.takeownershiplock ( ticketid ,ownerid ,lockdate ) values ( @ticketid ,@ownerid ,getdate() ) if ( @@rowcount > 0 ) set @lock = 1 end select @lock commit transaction takeownership end try begin catch -- test whether transaction uncommittable. if xact_state() = 1 begin commit transaction takeownership set @lock = 1 select @lock end -- test whether transaction active , valid. if xact_state() = -1 begin rollback transaction takeownership set @lock = 0 select @lock end end catch end
Comments
Post a Comment