1. 程式人生 > >Using system view: sys.sysprocesses to check SqlServer's block and deadlock

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:

 

spid smallint SQL Server session ID.
kpid smallint Windows thread ID.
blocked smallint ID 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.
waittype binary(2) Reserved.
waittime bigint Current wait time in milliseconds.

0 = Process is not waiting.
lastwaittype nchar(32) A string indicating the name of the last or current wait type.
waitresource nchar(256) Textual representation of a lock resource.
dbid smallint ID of the database currently being used by the process.
uid smallint ID of the user that executed the command. Overflows or returns NULL if the number of users and roles exceeds 32,767.
cpu int Cumulative 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_io bigint Cumulative disk reads and writes for the process.
memusage int Number 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_time datetime Time at which a client process logged into the server.
last_batch datetime Last time a client process executed a remote stored procedure call or an EXECUTE statement.
ecid smallint Execution context ID used to uniquely identify the subthreads operating on behalf of a single process.
open_tran smallint Number of open transactions for the process.
status nchar(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.
sid binary(86) Globally unique identifier (GUID) for the user.
hostname nchar(128) Name of the workstation.
program_name nchar(128) Name of the application program.
hostprocess nchar(10) Workstation process ID number.
cmd nchar(16) Command currently being executed.
nt_domain nchar(128) Windows domain for the client, if using Windows Authentication, or a trusted connection.
nt_username nchar(128) Windows user name for the process, if using Windows Authentication, or a trusted connection.
net_address nchar(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_library nchar(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.
loginame nchar(128) Login name.
context_info binary(128) Data stored in a batch by using the SET CONTEXT_INFO statement.
sql_handle binary(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_start int Starting offset of the current SQL statement for the specified sql_handle.
stmt_end int Ending 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_id int ID of request. Used to identify requests running in a specific session.
page_resource binary(8) Applies to: SQL Server 2019 preview 

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

 

 

應用例項:

1. 檢查資料庫是否發生阻塞

先查詢哪個連結的 blocked 欄位不為0。如 SPID53的blocked 欄位不為0,而是 52。SPID 52 的 blocked 為0,就可以得出結論:此時有阻塞發生,53 被 52 阻塞住了。如果你發現一個連線的 blocked 欄位的值等於它自己,那說明這個連線正在做磁碟讀寫,它要等自己的 I/O 做完。

2. 查詢連結在那個資料庫上

檢查 dbid 即可。得到 dbid,可以執行以下查詢得到資料庫的名字:

Select name,dbid from master.sys.sysdatabases
3. 檢視此程序執行的SQL 是哪個,查詢問題原因

dbcc inputbuffer(spid);
4. KILL 掉當前導致阻塞的SQL

kill spid
5. sql阻塞程序查詢

select A.SPID as 被阻塞程序,a.CMD AS 正在執行的操作,b.spid AS 阻塞程序號,b.cmd AS 阻塞程序正在執行的操作

from master..sysprocesses a,master..sysprocesses b

where a.blocked<>0 and a.blocked= b.spid
exec sp_who 'active'--檢視系統內所有的活動程序 BLK不為0的為死鎖
exec sp_lock 60 --返回某個程序對資源的鎖定情況
SELECT object_name(1504685104)--返回物件ID對應的物件名
DBCC INPUTBUFFER (63)--顯示從客戶端傳送到伺服器的最後一個語句
6. SQL Server簡潔查詢正在執行的程序SQL

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查詢和Kill程序死鎖的語句

查詢死鎖程序語句

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

 

下面再給大家分享一段關於sqlserver檢測死鎖;殺死鎖和程序;檢視鎖資訊

--檢測死鎖

--如果發生死鎖了,我們怎麼去檢測具體發生死鎖的是哪條SQL語句或儲存過程?

--這時我們可以使用以下儲存過程來檢測,就可以查出引起死鎖的程序和SQL語句。SQL Server自帶的系統儲存過程sp_who和sp_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 '現在沒有阻塞和死鎖資訊' 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

--殺死鎖和程序

--如何去手動的殺死程序和鎖?最簡單的辦法,重新啟動服務。但是這裡要介紹一個儲存過程,通過顯式的呼叫,可以殺死程序和鎖。

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 '[email protected])

fetch next from #tb into @spid

end

close #tb

deallocate #tb

go

--用法

exec p_killspid 'newdbpy'

--檢視鎖資訊

--如何檢視系統中所有鎖的詳細資訊?在企業管理管理器中,我們可以看到一些程序和鎖的資訊,這裡介紹另外一種方法。

--檢視鎖資訊

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 ['[email protected]+']..sysobjects where [email protected]'

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 程序id=a.req_spid

,資料庫=db_name(rsc_dbid)

,型別=case rsc_type when 1 then 'NULL 資源(未使用)'

when 2 then '資料庫'

when 3 then '檔案'

when 4 then '索引'

when 5 then '表'

when 6 then '頁'

when 7 then '鍵'

when 8 then '擴充套件盤區'

when 9 then 'RID(行 ID)'

when 10 then '應用程式'

end

,物件id=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

 

 

 

--檢視還未提交的事務的SQL語句

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


 

 

檢視被鎖的表

select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName

from sys.dm_tran_locks where resource_type='OBJECT'

Column nameData typeDescriptionspidsmallintSQL 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.