MSSQL DMVs — SQL Statements Text

It is always good to see what was the last query of any sessions.

SELECT cs.session_id, cs.connect_time,
cs.last_read, cs.last_write, sp.loginame, sp.hostname,
TEXT
FROM sys.dm_exec_connections cs
INNER JOIN sys.sysprocesses sp ON cs.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(cs.most_recent_sql_handle) AS ST 
where sp.dbid = db_id('DB')

The fol­low­ing query will tell you what’s the run­ning at the moment.

    SELECT [Spid] = session_Id
	, ecid
	, [Database] = DB_NAME(sp.dbid)
	, [User] = nt_username
	, [Status] = er.status
	, [Wait] = wait_type
	, [Individual Query] = SUBSTRING (qt.text, 
             er.statement_start_offset/2,
	(CASE WHEN er.statement_end_offset = -1
	       THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
		ELSE er.statement_end_offset END - 
                                er.statement_start_offset)/2)
	,[Parent Query] = qt.text
	, Program = program_name
	, Hostname
	, nt_domain
	, start_time
    FROM sys.dm_exec_requests er
    INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
    CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
    WHERE session_Id > 50              -- Ignore system spids.
    AND session_Id NOT IN (@@SPID)     -- Ignore this current statement.
    ORDER BY 1, 2

No Comments

Post a Comment

Your email is never shared. Required fields are marked *

*