我基本上有一个应用程序,有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