• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    SQL2005查看死锁存储过程sp_who_lock

    发布者: 土豆服务器 | 发布时间: 2025-6-18 14:15| 查看数: 100| 评论数: 0|帖子模式

    下面是我整理的监控sql server数据库,在性能测试过程中是否出现死锁、堵塞的SQL语句,还算比较准备,留下来备用。
    调用方法:选中相应的数据库,执行exec sp_who_lock
    1. USE [master]
    2. GO
    3. SET ANSI_NULLS ON
    4. GO
    5. SET QUOTED_IDENTIFIER ON
    6. GO


    7. CREATE procedure [dbo].[sp_who_lock]
    8. as
    9. begin
    10. declare @spid int, @bl int, @intTransactionCountOnEntry int, @intRowcount int, @intCountProperties int, @intCounter int

    11. create table #tmp_lock_who (
    12.         id int identity(1,1),
    13.         spid smallint,
    14.         bl smallint
    15. )

    16. IF @@ERROR<>0 RETURN @@ERROR

    17. insert into #tmp_lock_who(spid,bl) select 0 ,blocked
    18.         from (select * from sysprocesses where blocked>0 ) a
    19.         where not exists(select * from (select * from sysprocesses where blocked>0 ) b
    20.         where a.blocked=spid)
    21.         union select spid,blocked from sysprocesses where blocked>0

    22. IF @@ERROR<>0 RETURN @@ERROR

    23. -- 找到临时表的记录数
    24. select @intCountProperties = Count(*),@intCounter = 1
    25. from #tmp_lock_who

    26. IF @@ERROR<>0 RETURN @@ERROR

    27. if @intCountProperties=0
    28.         select '现在没有阻塞和死锁信息' as message

    29. -- 循环开始
    30. while @intCounter <= @intCountProperties
    31. begin
    32.         -- 取第一条记录
    33.         select @spid = spid,@bl = bl
    34.         from #tmp_lock_who where Id = @intCounter
    35.         begin
    36.                 if @spid =0
    37.       select '引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + '进程号,其执行的SQL语法如下'
    38.                 else
    39.       select '进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ '被' + '进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下'
    40.                 DBCC INPUTBUFFER (@bl )
    41.         end

    42.         -- 循环指针下移
    43.         set @intCounter = @intCounter + 1
    44. end

    45. drop table #tmp_lock_who

    46. return 0
    47. end
    复制代码

    来源:https://www.jb51.net/article/81527.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表