Sql server Insert语句上的死锁

Sql server Insert语句上的死锁,sql-server,stored-procedures,deadlock,Sql Server,Stored Procedures,Deadlock,使用存储过程将一系列记录从我的listview插入到我的SQL Server表中。但是我遇到了一个死锁,如下图所示 这是我的程序: declare @debtorCollectorHistoryId bigint set @debtorCollectorHistoryId = (Select top 1 id from FVOfficer with(nolock)

使用存储过程将一系列记录从我的listview插入到我的SQL Server表中。但是我遇到了一个死锁,如下图所示

这是我的程序:

declare @debtorCollectorHistoryId bigint

set @debtorCollectorHistoryId = (Select top 1 id 
                                 from FVOfficer with(nolock) 
                                 where debtorid = @debtorid 
                                 order by id desc)

if @currentFvCollectorid  is null
   set @currentFvCollectorid = (SELECT FvCollectorID 
                                from Debtor with(nolock) 
                                where id = @debtorid)

if @assignon is null
   set @assignon = GETDATE()

      print @debtorCollectorHistoryId
       print @currentFvCollectorid
      print @newFvCollectorid



    if @currentFvCollectorid <> @newFvCollectorid
    BEGIN
        if @currentFvCollectorid <> 0
        Begin   
            update FVOfficer 
            set terminateon = GetDate()
            where id = @debtorCollectorHistoryId
        End

        Begin
        --create new Collector History for new collector
        --NOTE: CurrentCollectorID is a previous collectorID for new Collector History

        insert into FVOfficer (debtorid, prevCollectorID, collectorid, assignon, terminateon, loginID)
        values (@debtorid,@currentFvCollectorid, @newFvCollectorid, GetDate(), null, @loginID)
        print' create new Collector History for new FV collector'

        exec dbo.[ValidatePrevFVCollectorByDebtorID] @debtorid
    end
    begin
        print @debtorid
        update Debtor set FVCollectorid = @newFvCollectorid where id = @debtorid 
    end

抱歉,我将错误的进程发布为我的“ValidatePrevFvCollectorByDeTorId”。经过仔细考虑。我知道锁发生在以下过程中:ValidatePrevFvCollectorByDeTorId

 DECLARE LOOPHISTORY_CURSOR CURSOR
        FOR  SELECT ID,DEBTORID,COLLECTORID,ASSIGNON FROM FVOFFICER 
        WHERE DEBTORID = @ID ORDER BY ID ASC
    OPEN LOOPHISTORY_CURSOR
债务人身份证被锁在上面。由于我在循环中执行大容量插入,因此调用了一个新的插入实例,但是在上一个任务/游标上锁定了债务人ID。首先

1我在select语句中添加了带有(nolock)的关键字,如下所示

SELECT ID,DEBTORID,COLLECTORID,ASSIGNON FROM FVOFFICER with(nolock)
                WHERE DEBTORID = @ID ORDER BY ID ASC
  • 然后,我在FVOfficer表的debortorid列上添加了一个非聚集索引,以提高select语句的速度。我跑完后,僵局没有发生
    警官身上有触发器吗?没有,长官。FVOfficer上没有触发器。如果你在插入后注释掉所有内容,死锁会消失吗?不,先生,没有尝试,我在想,因为我的快照打印了“为新FV收集器创建新收集器历史记录”的打印。那么可能是我表中的错误。然后我意识到下面的过程是一种使用游标的过程。可能是它锁定了@debtorid,然后需要在另一个新行中连续插入它吗?我想我会试着评论一下,看看。@Marko。我添加了第二个程序。这可能与我的问题有关吗?先生,请指教。
    SELECT ID,DEBTORID,COLLECTORID,ASSIGNON FROM FVOFFICER with(nolock)
                    WHERE DEBTORID = @ID ORDER BY ID ASC