SQL Server Query History – How to Retrieve and Analyze

sql serversql-server-2008

I have used below query to get the history queries on ran SQL Server but it's not giving me the whole history it just returns queries ran on nearly about last 1/2 an hour. I want to get the queries ran on week ago. Is there any solution?

SELECT  dest.text, deqs.last_execution_time
FROM    sys.dm_exec_query_stats AS deqs
        CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE    dest.text NOT LIKE '%dest.text%' 
         order by deqs.last_execution_time desc

Best Answer

I believe this is handled internally in SQL Server's query cache using memory available on the system. I know you can empty all of the cache by running the following:

DBCC FREEPROCCACHE WITH NO_INFOMSGS;

I just don't think you can alter how many queries it's saving.

Good luck.