添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Sql Server死锁和阻塞的监控和处理

1.查询是否有资源占用:

一、sys.dm_tran_locks表中的request_session_id(spid)为-2时,证明是分布式事务锁,即中 间件操作了锁定。

二、查询表锁并删除

SELECT request_session_id spid,OBJECT_NAME (resource_associated_entity_id)tableName

FROM sys.dm_tran_locks

WHERE resource_type='OBJECT'

KILL 100 spid

三、查询行锁(RID)、页锁(PAGE)、索引行锁(KEY)

1、根据表名查询表中的行、页、索引锁

SELECT request_session_id,request_owner_guid,*

FROM sys.partitions a

INNER JOIN sys.dm_tran_locks b ON a.hobt_id=b.resource_associated_entity_id

WHERE object_id=OBJECT_ID('SyncLogs')

2、分布式锁删除

KILL 'B7443ED4-A596-482A-899A-775845D2A29C' request_owner_guid

3、非分布式锁删除

kill request_session_id


2建存储过程看是否存在进程阻塞

存储过程:


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 '\现在没有阻塞和死锁信息\' as message


-- 循环开始

while @intCounter <= @intCountProperties

begin

-- 取第一条记录

select @spid = spid,@bl = bl

from #tmp_lock_who where Id = @intCounter

begin

if
@spid =0

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

else

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




GO




调用:

EXEC sp_who_lock




3开启sql Server的跟踪,查到具体的阻塞进程进行分析

选择默认模版

选择事件时,加上LOCK的相关事件


根据第二步查到的阻塞进程号,到这里找到相应的SQL,具体分析 :

1. 加索引

2. Select 加
with(nolock)

3. Where 条件尽量以主键ID为条件

4. 大数据量提交时,最好分批次提交,300一次(需要测试出最佳值)具体业务具体分析

发布于 2018-02-01 17:02