Sqlserver 锁表查询代码记录


--方法1
WITH
CTE_SID ( BSID, SID, sql_handle ) AS ( SELECT blocking_session_id , session_id , sql_handle FROM sys.dm_exec_requests WHERE blocking_session_id <> 0 UNION ALL SELECT A.blocking_session_id , A.session_id , A.sql_handle FROM sys.dm_exec_requests A JOIN CTE_SID B ON A.SESSION_ID = B.BSID ) SELECT C.BSID , C.SID , S.login_name , S.host_name , S.status , S.cpu_time , S.memory_usage , S.last_request_start_time , S.last_request_end_time , S.logical_reads , S.row_count , q.text FROM CTE_SID C JOIN sys.dm_exec_sessions S ON C.sid = s.session_id CROSS APPLY sys.dm_exec_sql_text(C.sql_handle) Q ORDER BY sid



--方法二

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 print @@ERROR

 

 insert into #tmp_lock_who(spid,bl) select  0 ,blocked

   from (select * from sysprocesses where  blocked>0 ) a 

   where not exists(select * from (select * from sysprocesses where  blocked>0 ) b 

   where a.blocked=spid)

   union select spid,blocked from sysprocesses where  blocked>0



 IF @@ERROR<>0 print @@ERROR 

  

-- 找到临时表的记录数
 select  @intCountProperties = Count(*),@intCounter = 1

 from #tmp_lock_who

 

 IF @@ERROR<>0 print @@ERROR 

 

 if @intCountProperties=0

  select N'现在没有阻塞和死锁信息' as message



-- 循环开始
while @intCounter <= @intCountProperties

begin

-- 取第一条记录
  select  @spid = spid,@bl = bl

  from #tmp_lock_who where Id = @intCounter 

 begin

  if @spid =0 

            select N'引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + N'进程号,其执行的SQL语法如下'

 else

            select N'进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ N'被进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +N'阻塞,其当前进程执行的SQL语法如下'

 DBCC INPUTBUFFER (@bl )

 end 



-- 循环指针下移
 set @intCounter = @intCounter + 1

end



drop table #tmp_lock_who
 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM