代码
USE [master]
GO
/****** 对象: StoredProcedure [dbo].[sp_who_lock] 脚本日期: 08/14/2008 18:14:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
--
Author:
--
Create date: 2008-08-12
--
Description: 数据库死锁状况检查
--
建议用txt方式查看结果,sql语句显示不全的请修改企业管理器本身的配置,
--
在tools--option--query result--SQL server--result to text中修改
--
=============================================
Create procedure [dbo].[sp_who_lock]
as
begin
set nocount on
declare @spid int,@bl int,
@intCountProperties int,
@intCounter int,
@waittime bigint,
@hostname nvarchar(128)

--建立临时表
create table #tmp_lock_who (
id
int identity(1,1),
spid
smallint,
bl
smallint,
waittime
bigint,
hostname
nvarchar(128))

IF @@ERROR<>0 RETURN @@ERROR

insert into #tmp_lock_who(spid,bl,waittime,hostname)
--死锁内容
select 0 ,blocked,waittime,hostname
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,waittime,hostname 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 N'现在没有阻塞和死锁信息' as message
else
select N'当前有' + convert(varchar(10),@intCountProperties) + '条阻塞和死锁信息' as message

-- 循环开始
while @intCounter <= @intCountProperties
begin
-- 取第一条记录
select @spid = spid,@bl = bl,@waittime=waittime,@hostname=hostname
from #tmp_lock_who where Id = @intCounter
begin
if @spid =0
begin
select N'引起数据库死锁的是进程: '+ CAST(@bl AS VARCHAR(10))
+ N',已运行' + cast(@waittime as varchar(20))
+ N'毫秒,客户端:' + rtrim(@hostname) + ',其执行的SQL语法如下'
end
else
begin
select N'进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ N'' + N'进程号SPID:'
+ CAST(@bl AS VARCHAR(10)) +N'阻塞,已运行' + cast(@waittime as varchar(20))
+ N'毫秒,客户端:' + rtrim(@hostname) + ',其当前进程执行的SQL语法如下'
end

-- 打印sql语句
DBCC INPUTBUFFER (@bl)
end

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

--删除临时表
drop table #tmp_lock_who
end

 

posted on 2010-11-09 16:45  秋来九月八  阅读(200)  评论(0编辑  收藏  举报