To find the last executed query in SQL Server, you can use Dynamic Management Views (DMVs). Below is an example query to retrieve the most recently executed query:
Sql
SELECT
deqs.creation_time,
deqs.last_execution_time,
dest.text AS query_text,
dest.dbid,
dest.objectid
FROM
sys.dm_exec_query_stats AS deqs
CROSS APPLY
sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY
deqs.last_execution_time DESC;
Explanation:
sys.dm_exec_query_stats: Contains execution statistics for cached query plans.sys.dm_exec_sql_text: Retrieves the SQL text of the query.last_execution_time: Indicates the last time the query was executed.ORDER BY deqs.last_execution_time DESC: Ensures the most recent query appears at the top.
Notes:
- This query retrieves data from the query cache, so if the cache is cleared (e.g., due to server restart or memory pressure), the information might not be available.
- For more persistent tracking, consider enabling SQL Server Audit or Extended Events.
Let me know if you'd like further clarification! 😊
No comments:
Post a Comment