sql – 行锁 – 手动使用它们

前端之家收集整理的这篇文章主要介绍了sql – 行锁 – 手动使用它们前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我基本上有一个应用程序,有5个线程,每个都从表中读取.查询是表中的一个简单的SELECT TOP 1 *,但我想强制执行锁定,以便下一个线程将从表中选择下一条记录而不是锁定的记录.当应用程序完成任务后,它将更新锁定的记录并释放锁定并再次重复该过程.这可能吗?

解决方法

我建议的方法是在记录中有一个字段,表示记录是否正在处理.然后实现“从队列中读取”sproc,执行以下操作,以确保没有2个进程获取相同的记录:
BEGIN TRANSACTION

-- Find the next available record that's not already being processed.
-- The combination of UPDLOCK and READPAST hints makes sure 2 processes don't 
-- grab the same record,and that processes don't block each other.
SELECT TOP 1 @ID = ID
FROM YourTable WITH (UPDLOCK,READPAST)
WHERE BeingProcessed = 0

-- If we've found a record,set it's status to "being processed"
IF (@ID IS NOT NULL)
    UPDATE YourTable SET BeingProcessed = 1 WHERE ID = @ID

COMMIT TRANSACTION

-- Finally return the record we've picked up
IF (@ID IS NOT NULL)
    SELECT * FROM YourTable WHERE ID = @ID

有关这些表提示的更多信息,请参阅MSDN

原文链接:https://www.f2er.com/mssql/84227.html

猜你在找的MsSQL相关文章