行锁 - 手动使用它们

时间:2010-02-19 10:01:26

标签: sql sql-server sql-server-2008

我基本上有一个应用程序有5个线程,每个线程从表中读取。查询是表中的一个简单的SELECT TOP 1 *,但我想强制执行一个锁,以便下一个线程将从表中选择下一条记录而不是锁定的记录。当应用程序完成任务后,它将更新锁定的记录并释放锁定并再次重复该过程。这可能吗?

3 个答案:

答案 0 :(得分:8)

我建议的方法是在记录中有一个字段,表示记录是否正在处理。然后实现“从队列中读取”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

答案 1 :(得分:0)

Sql Server中的

Service Broker Queues专门用于解决这种情况。

必须锁定表和行似乎是实现此功能的向后方式。

答案 2 :(得分:0)

有关此技术的更多详细信息"使用READPAST和UPDLOCK处理SQL Server中的数据队列"

https://www.mssqltips.com/sqlservertip/1257/processing-data-queues-in-sql-server-with-readpast-and-updlock/