自动处理数据库死锁

当数据库数据多,体积大,或者数据库结构设计庞杂,触发器多,此时会经常性的发生数据死锁。

以下编写了一个自动处理数据库死锁的存储过程,供大家学习指正。

---who表要先建好

ALTER PROCEDURE [dbo].[usp_kill_lock]

AS
BEGIN

DELETE who
    
INSERT INTO Who
EXEC sp_who


DECLARE
    @spid AS INT,
    @blk AS INT,
    @blk_lock as int,
    @str varchar(20)

    
-- 声明游标
DECLARE C_Who_Lock CURSOR FAST_FORWARD FOR
    SELECT spid,blk
    FROM Who
    ORDER BY spid;
    
OPEN C_Who_Lock;

-- 取第一条记录
FETCH NEXT FROM C_Who_Lock INTO @spid,@blk;

WHILE @@FETCH_STATUS=0
BEGIN
    -- 操作
    if @blk != 0
    begin
    select @blk_lock= blk from who where spid =@blk
       if @blk_lock = 0
       begin
       set @str = 'kill'+' ' +cast(@blk as varchar)
       exec usp_kill_spid @str
       return '干掉了进程号:'+ cast(@blk as varchar);        
       end  
    end
    -- 取下一条记录
    FETCH NEXT FROM C_Who_Lock INTO @spid,@blk;
END

-- 关闭游标
CLOSE C_Who_Lock;

-- 释放游标
DEALLOCATE C_Who_Lock;


END


--select * from who
--exec usp_kill_lock

你可能感兴趣的:(SQL)