这个需要一些解释。我所做的是在 SQL Server 2005 中创建一个特定的自定义消息队列。我有一个包含消息的表,其中包含确认和完成的时间戳。调用者执行以获取队列中下一条消息的存储过程也会确认该消息。到目前为止,一切都很好。好吧,如果系统正在经历大量事务(每分钟数千个),那么是否有可能在另一个存储过程的执行已准备好自己确认消息的同时,一条消息被另一个存储过程的执行所确认?让我通过在存储过程中显示我的 SQL 代码来提供帮助:
--Grab the next message id
declare @MessageId uniqueidentifier
set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands);
--Acknowledge the message
update ActionMessages
set AcknowledgedTime = getdate()
where ActionMessageId = @MessageId
--Select the entire message
...
...
在上面的代码中,同时运行的另一个存储过程不能获取相同的 id 并尝试同时确认它吗?我可以(或者应该)实现某种锁定以防止另一个存储过程确认另一个存储过程正在查询的消息吗?
哇,这一切有意义吗?有点难以用言语表达...
最佳答案
类似这样的事情
--Grab the next message id
begin tran
declare @MessageId uniqueidentifier
select top 1 @MessageId = ActionMessageId from UnacknowledgedDemands with(holdlock, updlock);
--Acknowledge the message
update ActionMessages
set AcknowledgedTime = getdate()
where ActionMessageId = @MessageId
-- some error checking
commit tran
--Select the entire message
...
...
关于sql-server - 如何在 SQL Server 2005 中锁定表?我应该这样做吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57625/