SQL SERVER – Find Currently Running Query – T-SQL

This is the script which I always had in my archive. Following script find out which are the queries running currently on your server. I use it whenever I need to find a currently running query that is taking too long.

SQL SERVER - Find Currently Running Query - T-SQL

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext 

While running above query if you find any query which is running for long time it can be killed using following command.

KILL [session_id]

What to Check Before You Kill a Currently Running Query

This script shows only requests that are active right now. A session that is connected but idle will not appear, and you will also see your own query in the list, along with some background system work. The list is a snapshot, so run it two or three times before deciding anything. To hide your own row, add WHERE req.session_id != @@SPID to the script.

Before you stop anything, add a few more columns to the list. blocking_session_id tells you if the request is stuck behind another session, wait_type tells you what it is waiting on, and start_time shows when it began. Both cpu_time and total_elapsed_time are in milliseconds. Many times the long query is only the victim, and the real problem is the session blocking it.

Killing a session is not free. SQL Server has to roll back all the work that the query did in its open transaction, and a rollback can take as long as the work itself, sometimes longer. You can watch its progress with KILL 53 WITH STATUSONLY, using the real session number instead of 53.

A few rules I follow:

  • Never kill a backup, restore or index rebuild without knowing what it is doing and how far it has gone.
  • Talk to the owner of the session first when you can. The host name and login name are in sys.dm_exec_sessions.
  • Save the query text before killing it, so you can tune it later and stop the same problem from coming back.

One more note: you need VIEW SERVER STATE permission to see the requests of other sessions. Without it, the script shows only your own work, which can make a busy server look strangely quiet.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Scripts, SQL Server Security
Previous Post
SQL SERVER – 2008 – 2005 – Find Longest Running Query – TSQL
Next Post
SQL SERVER – sqlcmd – Using a Dedicated Administrator Connection to Kill Currently Running Query

Related Posts

60 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.