这是我的代码,我正在寻找在更新时不锁定记录的最佳方法。
Declare @maxRowId int
Set @maxRowId=0
Declare @rowIndex int
Set @rowIndex=1
Declare @recordId bigint
Set @recordId=0
Begin Try
Declare @ReservedTickets table(RowId int, Id bigint,TicketCodeId nvarchar(100), Status nvarchar(100),DateTimeReserved datetime)
insert into @ReservedTickets
select ROW_NUMBER() OVER (ORDER BY Id) RowId,Id ,TicketCodeId, Status, DateTimeReserved
from [dbo].[Ticket] with(nolock)
where status='reserved' and
datetimeReserved <= DATEADD(minute, -30, getdate())
select @maxRowId=max(RowId) from @ReservedTickets
while @rowIndex<=@maxRowId
BEGIN
Select @recordId=Id from @ReservedTickets where Rowid=@rowIndex
Begin TRAN
UPDATE upd_Ticket
set
upd_Ticket.Status='available',
upd_Ticket.DateTimeReserved=null,
RequestReference=null
from [dbo].[Ticket] upd_Ticket
INNER JOIN [dbo].[Ticket] slct_Ticket with(nolock)
ON upd_Ticket.Id = slct_Ticket.Id
where slct_Ticket.Id= @recordId and
slct_Ticket.status='reserved' and
slct_Ticket.datetimeReserved <= DATEADD(minute, -30, getdate())
Commit TRAN
set @rowIndex=@rowIndex+1
END
select RV.Id, RV.status 'InitialStatus' ,V.status 'UpdatedStatus', RV.DateTimeReserved
from @ReservedTickets RV
Left join [dbo].[Ticket] V on
RV.Id=v.Id