How can I query the historical execution records in SQL Server?
To check the historical execution records of SQL Server, you can use the following methods:
- Utilize the dynamic management view sys.dm_exec_query_stats to gather information on past query executions, including query text, execution counts, average execution time, etc. This view allows sorting and filtering based on metrics such as execution time, CPU time, logical reads, etc.
SELECT
creation_time,
last_execution_time,
total_logical_reads,
total_elapsed_time,
execution_count,
st.text
FROM
sys.dm_exec_query_stats AS qs
CROSS APPLY
sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY
last_execution_time DESC
- Using SQL Server Profiler: Profiler is a powerful tool that can be used to monitor and analyze SQL Server activities. Tracing sessions can be set up to capture executed queries and view their history.
- Using Extended Events: Extended Events is an event handler for SQL Server that can capture and analyze activities of the SQL Server engine. By using Extended Events, you can create event sessions to capture executed queries and view their history.
CREATE EVENT SESSION QueryHistory
ON SERVER
ADD EVENT sqlserver.sql_statement_completed
(
ACTION (sqlserver.sql_text)
)
ADD TARGET package0.event_file
(
SET filename = 'C:\Path\To\QueryHistory.xel'
)
WITH
(
MAX_MEMORY = 4096 KB,
EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS
);
- Third-party tools can also be used to query the historical execution records of SQL Server, such as SQL Server Management Studio and Idera SQL Diagnostic Manager.
You can choose any method and select a suitable query method based on your needs, then further analyze the results.