Is it possible to log the text of each query executed on SQL Server?
-
28-10-2019 - |
Question
We have this recurring situation where several times a week our application stops responding. What I would like to do is be able to view the text of the query running on SQL Server.
I can use sp_who
to see the open connections, but, it does not display the actual query text.
If I can see the query that is freezing my database I can have a starting point for optimization.
This happened a few minutes ago and our sys admin had to reboot the box. This rebooting is not sustainable.
What steps should I take?
I would like to see the actual text of the queries that are running on my server.
SQL Server 2000
Solution
use this while the block is happening:
SELECT
r.session_id AS spid
,r.cpu_time,r.reads,r.writes,r.logical_reads
,r.blocking_session_id AS BlockingSPID
,LEFT(OBJECT_NAME(st.objectid, st.dbid),50) AS ShortObjectName
,LEFT(DB_NAME(r.database_id),50) AS DatabaseName
,s.program_name
,s.login_name
,OBJECT_NAME(st.objectid, st.dbid) AS ObjectName
,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 SQLText
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text (sql_handle) st
WHERE r.session_id!=@@SPID
this will list all active SPIDs, who is blocking them and the SQL of each SPID
EDIT
this query is for SQL Server 2005+, initial question did not state SQL Server 2000
OTHER TIPS
See the article How to monitor blocking in SQL Server 2005 and in SQL Server 2000 for the definition of sp_blocker_pss08
(a SQL Server 2000 compatible script).