当前位置: 首页 > news >正文

Using system view: sys.sysprocesses to check SqlServer's block and deadlock

You also can read the Chinese version: 秋天的林子---SQLSERVER的阻塞和死锁

 

Sys.SysProcesses: it's a important system view, it can locate and resolve block and deadlock.

Some fields(it from MSDN):

 

spidsmallintSQL Server session ID.
kpidsmallintWindows thread ID.
blockedsmallintID of the session that is blocking the request. If this column is NULL, the request is not blocked, or the session information of the blocking session is not available (or cannot be identified).

-2 = The blocking resource is owned by an orphaned distributed transaction.

-3 = The blocking resource is owned by a deferred recovery transaction.

-4 = Session ID of the blocking latch owner could not be determined due to internal latch state transitions.
waittypebinary(2)Reserved.
waittimebigintCurrent wait time in milliseconds.

0 = Process is not waiting.
lastwaittypenchar(32)A string indicating the name of the last or current wait type.
waitresourcenchar(256)Textual representation of a lock resource.
dbidsmallintID of the database currently being used by the process.
uidsmallintID of the user that executed the command. Overflows or returns NULL if the number of users and roles exceeds 32,767.
cpuintCumulative CPU time for the process. The entry is updated for all processes, regardless of whether the SET STATISTICS TIME option is ON or OFF.
physical_iobigintCumulative disk reads and writes for the process.
memusageintNumber of pages in the procedure cache that are currently allocated to this process. A negative number indicates that the process is freeing memory allocated by another process.
login_timedatetimeTime at which a client process logged into the server.
last_batchdatetimeLast time a client process executed a remote stored procedure call or an EXECUTE statement.
ecidsmallintExecution context ID used to uniquely identify the subthreads operating on behalf of a single process.
open_transmallintNumber of open transactions for the process.
statusnchar(30)Process ID status. The possible values are:

dormant = SQL Server is resetting the session.

running = The session is running one or more batches. When Multiple Active Result Sets (MARS) is enabled, a session can run multiple batches. For more information, see Using Multiple Active Result Sets (MARS).

background = The session is running a background task, such as deadlock detection.

rollback = The session has a transaction rollback in process.

pending = The session is waiting for a worker thread to become available.

runnable = The task in the session is in the runnable queue of a scheduler while waiting to get a time quantum.

spinloop = The task in the session is waiting for a spinlock to become free.

suspended = The session is waiting for an event, such as I/O, to complete.
sidbinary(86)Globally unique identifier (GUID) for the user.
hostnamenchar(128)Name of the workstation.
program_namenchar(128)Name of the application program.
hostprocessnchar(10)Workstation process ID number.
cmdnchar(16)Command currently being executed.
nt_domainnchar(128)Windows domain for the client, if using Windows Authentication, or a trusted connection.
nt_usernamenchar(128)Windows user name for the process, if using Windows Authentication, or a trusted connection.
net_addressnchar(12)Assigned unique identifier for the network adapter on the workstation of each user. When a user logs in, this identifier is inserted in the net_address column.
net_librarynchar(12)Column in which the client's network library is stored. Every client process comes in on a network connection. Network connections have a network library associated with them that enables them to make the connection.
loginamenchar(128)Login name.
context_infobinary(128)Data stored in a batch by using the SET CONTEXT_INFO statement.
sql_handlebinary(20)Represents the currently executing batch or object.

Note This value is derived from the batch or memory address of the object. This value is not calculated by using the SQL Server hash-based algorithm.
stmt_startintStarting offset of the current SQL statement for the specified sql_handle.
stmt_endintEnding offset of the current SQL statement for the specified sql_handle.

-1 = Current statement runs to the end of the results returned by the fn_get_sql function for the specified sql_handle.
request_idintID of request. Used to identify requests running in a specific session.
page_resourcebinary(8)Applies to: SQL Server 2019 preview 

An 8-byte hexadecimal representation of the page resource if the waitresource column contains a page.

 

example of application:

1. Check DB if have blocked

first to find which process's blocked filed is not 0. example: if rSPID53's blocked filed is not 0, it equal 52 and SPID's blockd is 0, you can get the conclusion now: blocked occurs, the process 53 is blocked by 52. in another situation, if you found that the blocked filed same as itself, it means the process is reading and writing disk.

2. Which DB is the process

only check dbid, using the following query

Select name,dbid from master.sys.sysdatabases

3. check the process corresponding SQL code

dbcc inputbuffer(spid);
4. KILL the process

kill spid

5. sql blocked and process query

select A.SPID as 'the process is blocked', a.CMD AS 'execute type',b.spid AS 'blocked process',b.cmd 
from master..sysprocesses a,master..sysprocesses b
where a.blocked<>0 and a.blocked= b.spid
DBCC INPUTBUFFER(59   )

exec sp_who 'active'--all of system process and the process is blocked if BLK field is not 0
exec sp_lock SPID --Returns a process lock on the resource situation
SELECT object_name(1093578934)--Returns object ID corresponding object name 
DBCC INPUTBUFFER (63)--show the SPID's statement

6. SQL Server is running  sql statements

SELECT spid,
blocked,
DB_NAME(sp.dbid) AS DBName,
program_name,
waitresource,
lastwaittype,
sp.loginame,
sp.hostname,
a.[Text] AS [TextData],
SUBSTRING(A.text, sp.stmt_start / 2,
(CASE WHEN sp.stmt_end = -1 THEN DATALENGTH(A.text) ELSE sp.stmt_end
END - sp.stmt_start) / 2) AS [current_cmd]
FROM sys.sysprocesses AS sp OUTER APPLY sys.dm_exec_sql_text (sp.sql_handle) AS A
WHERE spid > 50
ORDER BY blocked DESC, DB_NAME(sp.dbid) ASC, a.[text];

 

SqlServer query deadlock process

select
request_session_id spid,
OBJECT_NAME(resource_associated_entity_id) tableName
from
sys.dm_tran_locks
where
resource_type='OBJECT'

 

as to sqlserver check deadlock kill lock

use master

go

create procedure sp_who_lock

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


select @intCountProperties = Count(*),@intCounter = 1

from #tmp_lock_who

IF @@ERROR<>0 RETURN @@ERROR

if @intCountProperties=0

select 'no block and deadlock now' as message

while @intCounter <= @intCountProperties

begin

select @spid = spid,@bl = bl

from #tmp_lock_who where Id = @intCounter

begin

if @spid =0

select 'DB deadlock is caused by : '+ CAST(@bl AS VARCHAR(10)) + 'its statement is:'

else

select 'SPID:'+ CAST(@spid AS VARCHAR(10))+ ' is blocked by ' + 'SPID:'+ CAST(@bl AS VARCHAR(10)) +',its statement is:'

DBCC INPUTBUFFER (@bl )

end

set @intCounter = @intCounter + 1

end

drop table #tmp_lock_who

return 0

end

 

--kill lock and process

use master

go

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_killspid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

drop procedure [dbo].[p_killspid]

GO

create proc p_killspid

@dbname varchar(200) 

as

declare @sql nvarchar(500)

declare @spid nvarchar(20)

declare #tb cursor for

select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname)

open #tb

fetch next from #tb into @spid

while @@fetch_status=0

begin

exec('kill '+@spid)

fetch next from #tb into @spid

end

close #tb

deallocate #tb

go


--exec p_killspid 'newdbpy'

 

--view some lock information

create table #t(req_spid int,obj_name sysname)

declare @s nvarchar(4000)

,@rid int,@dbname sysname,@id int,@objname sysname

declare tb cursor for

select distinct req_spid,dbname=db_name(rsc_dbid),rsc_objid

from master..syslockinfo where rsc_type in(4,5)

open tb

fetch next from tb into @rid,@dbname,@id

while @@fetch_status=0

begin

set @s='select @objname=name from ['+@dbname+']..sysobjects where id=@id'

exec sp_executesql @s,N'@objname sysname out,@id int',@objname out,@id

insert into #t values(@rid,@objname)

fetch next from tb into @rid,@dbname,@id

end

close tb

deallocate tb

select 'process id'=a.req_spid

,DB=db_name(rsc_dbid)

,'Type'=case rsc_type when 1 then 'NULL (no use)'

when 2 then 'DB'

when 3 then 'file'

when 4 then 'Index'

when 5 then 'table'

when 6 then 'page'

when 7 then 'key'

when 8 then 'expand the disk'

when 9 then 'RID(row ID)'

when 10 then 'application'

end

,rsc_objid

,b.obj_name

,rsc_indid

from master..syslockinfo a left join #t b on a.req_spid=b.req_spid

go

drop table #t

--view no commit transaction

USE master

GO

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT es.session_id, es.login_name, es.host_name, est.text

, cn.last_read, cn.last_write, es.program_name

FROM sys.dm_exec_sessions es

INNER JOIN sys.dm_tran_session_transactions st  

ON es.session_id = st.session_id

INNER JOIN sys.dm_exec_connections cn

ON es.session_id = cn.session_id

CROSS APPLY sys.dm_exec_sql_text(cn.most_recent_sql_handle) est

LEFT OUTER JOIN sys.dm_exec_requests er

ON st.session_id = er.session_id

AND er.session_id IS NULL

 

view which tables is locked

select   request_session_id   spid,OBJECT_NAME(resource_associated_entity_id) tableName  

from   sys.dm_tran_locks where resource_type='OBJECT'

 

转载于:https://www.cnblogs.com/ziqiumeng/p/10147403.html

相关文章:

  • JavaScript中for in 和for of的区别
  • 对于你们驳来驳去的《停止学习框架》,我有话说!
  • Linux下调整ext3分区大小【转】
  • 大快搜索获评“2018中国大数据基础软件领域领军企业”
  • leetcode讲解--894. All Possible Full Binary Trees
  • React降级配置及Ant Design配置
  • 解决iOS10的Safari下Meta设置user-scalable=no无效的方法
  • 中国智慧城市“热战”的2018
  • django之中间件及CSRF跨站请求伪造-68
  • Javascripit类型转换比较那点事儿,双等号(==)
  • Win7 64位 Hadoop单机模式安装
  • 技术发展面试
  • Android开发者必备:推荐一款助力开发的开源APP
  • 关于for循环的简单归纳
  • MongoDB介绍
  • 【译】理解JavaScript:new 关键字
  • CentOS 7 防火墙操作
  • leetcode-27. Remove Element
  • Otto开发初探——微服务依赖管理新利器
  • Python_OOP
  • scrapy学习之路4(itemloder的使用)
  • 大数据与云计算学习:数据分析(二)
  • 对话 CTO〡听神策数据 CTO 曹犟描绘数据分析行业的无限可能
  • 机器学习 vs. 深度学习
  • 批量截取pdf文件
  • 如何使用 OAuth 2.0 将 LinkedIn 集成入 iOS 应用
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 思考 CSS 架构
  • 微服务核心架构梳理
  • 系统认识JavaScript正则表达式
  • 学习ES6 变量的解构赋值
  • media数据库操作,可以进行增删改查,实现回收站,隐私照片功能 SharedPreferences存储地址:
  • 交换综合实验一
  • 支付宝花15年解决的这个问题,顶得上做出十个支付宝 ...
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • ​创新驱动,边缘计算领袖:亚马逊云科技海外服务器服务再进化
  • ​人工智能书单(数学基础篇)
  • ​直流电和交流电有什么区别为什么这个时候又要变成直流电呢?交流转换到直流(整流器)直流变交流(逆变器)​
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • (1)(1.9) MSP (version 4.2)
  • (LNMP) How To Install Linux, nginx, MySQL, PHP
  • (MonoGame从入门到放弃-1) MonoGame环境搭建
  • (附源码)ssm考生评分系统 毕业设计 071114
  • (十)DDRC架构组成、效率Efficiency及功能实现
  • (四) 虚拟摄像头vivi体验
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • .bat批处理(四):路径相关%cd%和%~dp0的区别
  • .NET : 在VS2008中计算代码度量值
  • .NET DevOps 接入指南 | 1. GitLab 安装
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .NET委托:一个关于C#的睡前故事
  • @RequestParam,@RequestBody和@PathVariable 区别
  • @SuppressWarnings(unchecked)代码的作用
  • [c++] 什么是平凡类型,标准布局类型,POD类型,聚合体
  • [C++]STL之map