转载

sql server阻塞查询语句

sql server的阻塞查询,主要来自sysprocesses。通常我们在处理时需要加入其它相关的视图或表如dm_exec_connections,dm_exec_sql_text。通过几个语句的查询,可以找到阻塞的语句。
查询阻塞
语句一
select bl.spid blocking_session,bl.blocked blocked_session,st.text blockedtext from (SELECT   spid ,blocked
   FROM (SELECT * FROM sys.sysprocesses WHERE   blocked>0 ) a
   WHERE not exists(SELECT *
                    FROM (SELECT *
                          FROM sys.sysprocesses
                          WHERE   blocked>0 ) b
                    WHERE a.blocked=spid)
   union SELECT spid,blocked
         FROM sys.sysprocesses
         WHERE   blocked>0) bl,(SELECT t.text ,c.session_id
         FROM sys.dm_exec_connections c 
         CROSS APPLY sys.dm_exec_sql_text (c.most_recent_sql_handle) t) st
 where bl.blocked = st.session_id

语句二
SELECT a.blocking_session_id, a.wait_duration_ms, a.session_id,b.text
FROM sys.dm_os_waiting_tasks a,
(SELECT t.text ,c.session_id
FROM sys.dm_exec_connections c 
CROSS APPLY sys.dm_exec_sql_text (c.most_recent_sql_handle) t) b 
WHERE  a.session_id = b.session_id and a.blocking_session_id IS NOT NULL

语句三,包含阻塞与被阻塞的sql脚本

select bl.spid blocking_session,bl.blocked blocked_session,st.text blockedtext,sb.text blockingtext
from
(SELECT   spid ,blocked
   FROM (SELECT * FROM sys.sysprocesses WHERE   blocked>0 ) a
   WHERE not exists(SELECT *
                    FROM (SELECT *
                          FROM sys.sysprocesses
                          WHERE   blocked>0 ) b
                    WHERE a.blocked=spid)
   union
 SELECT spid,blocked
         FROM sys.sysprocesses
         WHERE   blocked>0) bl,
(SELECT t.text ,c.session_id
         FROM sys.dm_exec_connections c 
         CROSS APPLY sys.dm_exec_sql_text (c.most_recent_sql_handle) t) st,
(SELECT t.text ,c.session_id
         FROM sys.dm_exec_connections c 
         CROSS APPLY sys.dm_exec_sql_text (c.most_recent_sql_handle) t) sb
 where bl.blocked = st.session_id and bl.spid = sb.session_id

查询死锁
select *
   from master..SysProcesses
  where db_Name(dbID) = '数据库名'
    and spId <> @@SpId
    and dbID <> 0
    and blocked >0;

正文到此结束
Loading...