查询SQLSERVER执行过的SQL记录(历史查询记录)

时间:2023-12-20 09:08:14

有的时候,需要知道近段时间SQLSERVER执行了什么语句,可以用下面的方法:

SELECT     TOP 1000 QS.creation_time, SUBSTRING(ST.text, (QS.statement_start_offset / 2) + 1,
((CASE QS.statement_end_offset WHEN - 1 THEN DATALENGTH(st.text) ELSE QS.statement_end_offset END - QS.statement_start_offset) / 2) + 1)
AS statement_text, ST.text, QS.total_worker_time, QS.last_worker_time, QS.max_worker_time, QS.min_worker_time
FROM sys.dm_exec_query_stats QS CROSS APPLY sys.dm_exec_sql_text(QS.sql_handle) ST
WHERE QS.creation_time BETWEEN '2017-09-09 10:00:00' AND '2017-09-11 18:00:00' AND ST.text LIKE '%%'
ORDER BY QS.creation_time DESC