数据库死锁查询及处理

创建存储过程sp_who_lock,查询死锁的进程

复制代码
create procedure sp_who_lock
WITH ENCRYPTION
as
begin
    declare @spid int,@bl int,
    @intTransactionCountOnEntry     int,
    @intRowcount             int,
    @intCountProperties         int,
    @intCounter             int
    create table #tmp_lock_who (
        id int identity(1,1),
        spid smallint,
        bl smallint)
    
    IF @@ERROR <> 0 RETURN @@ERROR

    insert into #tmp_lock_who(spid,bl) select spid,blocked from sysprocesses where  blocked <> 0

    IF @@ERROR <> 0 RETURN @@ERROR
    -- 找到临时表的记录数
    select @intCountProperties = Count(1),@intCounter = 1 from #tmp_lock_who
    IF @@ERROR <> 0 RETURN @@ERROR
    if @intCountProperties=0
        select '现在没有阻塞和死锁信息' as 'message'

    -- 循环开始
    while @intCounter = @intCountProperties
    begin
    -- 取第一条记录
        select     @spid = spid,@bl = bl
        from #tmp_lock_who where Id = @intCounter
        begin
            select '进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ ''
            + '进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下'
            DBCC INPUTBUFFER (@bl )
        end
        -- 循环指针下移
        set @intCounter = @intCounter + 1
    end
    drop table #tmp_lock_who
    return 0
end
View Code
复制代码

下面我们自己构建一个死锁进程:

复制代码
BEGIN TRANSACTION--开始事务

update   T_Users  set UserName='00000'  where UserId='123'

WAITFOR DELAY '01:00'; --指定1点执行 
View Code
复制代码

执行查询语句:

select * from T_Users where UserId='123'

这时会发现一直在执行查询。得不到查询结果,我们执行第一步创建的存储过程sp_who_lock.得到结果如下:

此时我们只需执行

kill 53

然后再执行查询语句就可以得到结果了。

 

posted @   年华若流矢  阅读(2807)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示