数据库死锁的解决办法
一、破壞死鎖的四個(gè)必要條件
二、如果發(fā)生死鎖,通過(guò)SQL語(yǔ)句關(guān)閉當(dāng)前發(fā)生死鎖的數(shù)據(jù)庫(kù)進(jìn)程
USE master --不能用 KILL 來(lái)取消您自己的進(jìn)程。
GO
/****** Object:? StoredProcedure [dbo].[p_Centaline_Who_Lock]??? Script Date: 03/23/2016 11:54:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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)??? --要關(guān)閉進(jìn)程的數(shù)據(jù)庫(kù)名
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
?
調(diào)用
exec p_killspid? '需要關(guān)閉進(jìn)程的數(shù)據(jù)庫(kù)名'? 當(dāng)強(qiáng)制關(guān)閉進(jìn)程后,死鎖也就沒(méi)有了
?
?
二、查看當(dāng)前數(shù)據(jù)庫(kù)下鎖的情況
CREATE Table #Who(
??? spid int,
??? ecid int,
??? [status] nvarchar(50),
??? loginname nvarchar(50),
??? hostname nvarchar(50),
??? blk int,
??? dbname nvarchar(50),
??? cmd nvarchar(50)
??? --request_ID int
??? );
?
CREATE Table #Lock(
??? spid int,
??? dpid int,
??? [objid] int,
??? indld int,
??? [Type] nvarchar(20),
??? [Resource] nvarchar(50),
??? Mode nvarchar(10),
??? [Status] nvarchar(10)
);
?
INSERT INTO #Who
??? EXEC sp_who active? --看哪個(gè)引起的阻塞,blk
INSERT INTO #Lock
??? EXEC sp_lock? --看鎖住了那個(gè)資源id,objid
?
DECLARE @DBName nvarchar(20);
SET @DBName='KF-BJAgencyAtt'
?
SELECT #Who.* FROM #Who WHERE dbname=@DBName
SELECT #Lock.* FROM #Lock
??? JOIN #Who
??????? ON #Who.spid=#Lock.spid
??????????? AND dbname=@DBName;
?
--最后發(fā)送到SQL Server的語(yǔ)句
DECLARE crsr Cursor FOR
??? SELECT blk FROM #Who WHERE dbname=@DBName AND blk<>0;
DECLARE @blk int;
open crsr;
FETCH NEXT FROM crsr INTO @blk;
WHILE (@@FETCH_STATUS = 0)
BEGIN
??? dbcc inputbuffer(@blk);
??? FETCH NEXT FROM crsr INTO @blk;
END
close crsr;
DEALLOCATE crsr;
?
--鎖定的資源
SELECT #Who.spid,hostname,objid,[type],mode,object_name(objid) as objName FROM #Lock
??? JOIN #Who
??????? ON #Who.spid=#Lock.spid
??????????? AND dbname=@DBName
??? WHERE objid<>0;
??? --SELECT * FROM?? #Lock
DROP Table #Who;
DROP Table #Lock;
查看死鎖實(shí)例
BEGIN tran
??????? UPDATE B SET age=age+1
??????? WaitFor Delay '00:00:05';
??????? SELECT * FROM A?????--執(zhí)行完之后有結(jié)果
在新建一個(gè)查詢(xún),執(zhí)行下面sql語(yǔ)句
BEGIN tran
????????? UPDATE a SET dd=dd+1
????????? WaitFor Delay '00:00:05';
????????? SELECT * FROM B
????? ROLLBACK tran?? --當(dāng)執(zhí)行的時(shí)候會(huì)一直執(zhí)行下去
查看出現(xiàn)死鎖語(yǔ)句
??
?
轉(zhuǎn)載于:https://www.cnblogs.com/starts/p/5311936.html
總結(jié)
以上是生活随笔為你收集整理的数据库死锁的解决办法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [转]linux tr命令详解
- 下一篇: Java基本知识