How to identify blocking processes/long running queries in SQL server?
Blocking occurs when a process hold a lock and other process has to wait till the first process completes.
Sometime, when we execute any stored procedures or a query and expect that to complete quickly but it kept running for a long time in this situation we do not have any other option rather than stopping a query or stored procedure, It just happens due to process block issues.
Lets try to understand it with the help of an example.
To implement a blocked processes scenario, we will try to update one record in a table under begin tran block but will not commit the transaction that will hold update lock on a table and process kept running until transaction is not committed and during that time we will update same record in another session .
As you can see, we have updated a record in a table under begin transaction block but not committed yet.
use Sqltutorials Begin Tran update dbo.Customer set firstName = 'Jon M' where customerKey =11000
Now, open another query editor window ) and try to update same record in a table, and you see the update query keep running and not updating record.
use Sqltutorials update dbo.Customer set firstName = 'Jon M' where customerKey =11000
Lets identify the those blocking processesย .
You can execute SP_who2 to get the blocked processes Details.
As You can see blkby is – 53, it means processes Id -53 (That is first query where you have ran a update query under begin transaction but not committed ) is blocking the execution of processes Id – 54 ( that is second query ) .
sp_who2
Exec sp_who2
Here we identified that the processes id is blocking the second query execution so we can kill the processes id -53, using kill spidย command as given below
kill 53
As soon as we kill the blocked processes , the second query executed successfully and update the record.
We can also use SysProcesses to get the blocked processes details –
SELECT spid, ย ย ย ย ย ย blocked as blockingProcessesId, ย ย ย ย ย ย (SELECT Systxt1.TEXT ย ย ย ย ย ย ย ย FROMย ย sysprocesses st ย ย ย ย ย ย ย ย ย ย ย ย ย ย CROSS apply sys.Dm_exec_sql_text(sql_handle) systxt1 ย ย ย ย ย ย ย ย WHEREย ย spid = p.blocked) AS blockingQuerytxt, ย ย ย ย ย PROGRAM_NAME,ย loginame, DB_NAME(p.dbid) as DatabaseName,ย Systxt2.TEXT as Querytxt FROMย ย sysprocesses p ย ย ย ย ย ย CROSS apply sys.Dm_exec_sql_text(sql_handle) Systxt2 WHEREย ย blocked <> 0
9,743 total views, 2 views today