查詢Sqlserver資料庫死鎖的乙個儲存過程

2022-02-16 02:27:31 字數 2881 閱讀 8252

使用sqlserver作為資料庫的應用系統,都避免不了有時候會產生死鎖, 死鎖出現以後,維護人員或者開發人員大多只會通過sp_who來查詢死鎖的程序,然後用sp_kill殺掉。利用sp_who_lock這個儲存過程,可以很方便的知道哪個程序出現了死鎖,出現死鎖的問題在**.

建立sp_who_lock儲存過程 

create

procedure

sp_who_lock

asbegin

declare

@spid

intdeclare

@blk

intdeclare

@count

intdeclare

@index

intdeclare

@lock

tinyint

set@lock=0

create

table

#temp_who_lock

(

id intidentity(1,1

),

spid

int,

blk

int)

if@@error

<>

0return

@@error

insert

into

#temp_who_lock(spid,blk)

select

0,blocked

from (select

*from master..sysprocesses where blocked>

0)a

where

notexists(select

*from master..sysprocesses where a.blocked =spid and blocked>

0)

union

select spid,blocked from master..sysprocesses where blocked>0if

@@error

<>

0return

@@error

select

@count

=count(*),@index=1

from

#temp_who_lock if

@@error

<>

0return

@@error

if@count=0

begin

select

'沒有阻塞和死鎖資訊

'return

0end

while

@index

<=

@count

begin

ifexists(select

1from #temp_who_lock a where id>

@index

andexists(select

1from #temp_who_lock where id<=

@index

and a.blk=

spid))

begin

set@lock=1

select

@spid

=spid,@blk

=blk from #temp_who_lock where id=

@index

select

'引起資料庫死鎖的是: '+

cast(@spid

asvarchar(10)) +

'程序號,其執行的sql語法如下

'select

@spid, @blk

dbcc inputbuffer(@spid

)

dbcc inputbuffer(@blk

)

endset@index

=@index+1

endif

@lock=0

begin

set@index=1

while

@index

<=

@count

begin

select

@spid

=spid,@blk

=blk from #temp_who_lock where id=

@index

if@spid=0

select

'引起阻塞的是:'+

cast(@blk

asvarchar(10))+

'程序號,其執行的sql語法如下

'else

select

'程序號spid:'+

cast(@spid

asvarchar(10))+'被

'+'程序號spid:'+

cast(@blk

asvarchar(10)) +

'阻塞,其當前程序執行的sql語法如下

'dbcc inputbuffer(@spid

)

dbcc inputbuffer(@blk

)

set@index

=@index+1

endend

drop

table

#temp_who_lock

return

0end

go

在查詢分析器中執行:

直到最後的結果為:

**:

SQL Server資料庫查詢

開啟我們的sql server資料庫,找到要查詢的資料庫表,右鍵單擊然後選擇新建查詢,select 選擇我們要查詢的表sys academe學院表 聯合 sys class.classname班級表的班級名稱和sys grade.gradename年級表的年級編號來查詢出資料。下面是查詢的 sele...

SQL Server 跨資料庫查詢

語句 select from 資料庫a.dbo.表a a,資料庫b.dbo.表b b where a.field b.field dbo 可以省略 如 select from 資料庫a.表a a,資料庫b.表b b where a.field b.field sqlserver資料庫 這句是對映乙個...

查詢SQL SERVER 資料庫版本

select substring cast serverproperty productversion as nvarchar 128 1,charindex cast serverproperty productversion as nvarchar 128 1 1 8 對應 sql server...