Transact-SQL: processi bloccanti e relative query

Utilizzando SQL Server Enterprise Manager è possibile visualizzare l’attività corrente del server,  sotto forma di elenco di processi e loro situazione:

Attività Corrente
Immagine

Può capitare che processi siano bloccati da altri processi. Ed è possibile visualizzare l’ultimo comando TSQL eseguito dai processi:

Proprietà

Unendo le informazioni trovate in questi due siti

http://www.sqlservercentral.com/Forums/Topic365627-146-1.aspx

http://www.kodyaz.com/articles/identify-kill-blocking-sql-server-processes.aspx

ho realizzato uno script che mostra i processi bloccanti, ed il relativo comando TSQL:

use master
GO
declare @spid smallint

select * from sysprocesses (nolock) where blocked = 0 and spid in (
select blocked from sysprocesses (nolock) where blocked <> 0 )

DECLARE c_curs CURSOR FOR
select spid from sysprocesses (nolock) where blocked = 0 and spid in (
select blocked from sysprocesses (nolock) where blocked <> 0
)

OPEN c_curs
FETCH NEXT FROM c_curs
INTO @spid

WHILE @@FETCH_STATUS = 0
BEGIN

dbcc inputbuffer(@spid)

FETCH NEXT FROM c_curs
INTO @spid

END --while

CLOSE c_curs
DEALLOCATE c_curs

Breve spiegazione: prima viene eseguita la query:

select * from sysprocesses (nolock) where blocked = 0 and spid in (
select blocked from sysprocesses (nolock) where blocked <> 0 )

che restituisce l’elenco dei processi bloccanti, poi sulla stessa query viene definito un cursore, e di ogni processo vado a prendere il comando TSQL che sta eseguendo:

dbcc inputbuffer(@spid)

Qualche nota:

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>