您如何锁定 SQL Server 2005 中的表,我什至应该这样做吗?

How do you lock tables in SQL Server 2005, and should I even do it?(您如何锁定 SQL Server 2005 中的表,我什至应该这样做吗?)
本文介绍了您如何锁定 SQL Server 2005 中的表,我什至应该这样做吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这个需要一些解释.我所做的是在 SQL Server 2005 中创建一个特定的自定义消息队列.我有一个包含确认和完成时间戳的消息表.调用者为获取队列中的下一条消息而执行的存储过程也会确认该消息.到现在为止还挺好.好吧,如果系统正在经历大量事务(每分钟数千次),是否有可能一条消息被另一个存储过程的执行确认而另一个准备好自己这样做?让我通过在存储过程中显示我的 SQL 代码来提供帮助:

This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc:

--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并尝试同时确认它吗?我可以(或应该)实施某种锁定以防止另一个存储的 proc 确认另一个存储的 proc 正在查询的消息?

In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying?

哇,这有什么道理吗?有点难以用语言表达...

Wow, did any of this even make sense? It's a bit difficult to put to words...

推荐答案

类似这样的事情

--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 2005 中的表,我什至应该这样做吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Number of working days between two dates(两个日期之间的工作日数)
How do I use dateadd to get the first day of last year?(如何使用 dateadd 获取去年的第一天?)
SQL- Count occurrences of a specific word within all stored procedures(SQL- 计算所有存储过程中特定单词的出现次数)
SQL query to make a column of numbers a string(使一列数字成为字符串的 SQL 查询)
T-SQL: Best way to replace NULL with most recent non-null value?(T-SQL:用最新的非空值替换 NULL 的最佳方法?)
Count days in date range with set of exclusions which may overlap(使用一组可能重叠的排除项计算日期范围内的天数)