
This image is AI Generated
Knowing which SQL queries are currently running can help you monitor performance, detect blocking, and troubleshoot slowdowns. In this post, you'll learn how to list active queries using a simple script with SQL Server's built-in system views
select
s.session_id,
r.status,
r.blocking_session_id,
SUBSTRING(st.text,(r.statement_start_offset/2)+1,
(
(
CASE r.statement_end_offset
when -1
THEN Datalength(st.text)
else r.statement_end_offset
END -r.statement_start_offset
)/2
)+1) AS Statment_text,
COALESCE(Quotename(DB_Name(st.dbid))+N'.'+Quotename(object_schema_name(st.objectid,st.dbid))+N'.'+
QUotename(Object_name(st.objectid,st.dbid)),'') AS Command_text,
r.wait_type,
wait_resource
,r.wait_time/(1000.0) AS WaitTimeInSec,
r.cpu_time,
r.logical_reads,
r.reads,
r.writes,
r.total_elapsed_time/(1000.0) AS Elapsedtimeinsec,
r.command,
s.login_name,
s.host_name,
s.program_name
,s.host_process_id,
s.last_request_end_time
from sys.dm_exec_sessions as s
inner join SYS.dm_exec_requests AS r
ON r.session_id = S.session_id
Cross apply sys.dm_exec_sql_text(r.sql_handle) as ST
WHERE r.session_id <> @@SPID
--and r.status like '%runn%'
ORDER BY r.cpu_time
,r.status,
r.blocking_session_id,
s.session_id