Sql-server – SQL Server 2008 Query Saved in Logs

querysql-server-2008transaction-log

Every time I create a query and run it to create a report I save the query in my Projects folder in case I have to rerun the query in the future or if I have to modify it for any reason but it seems that for some reason a query which I ran sometime in mid June was not saved. I need to see the code I used in the query because I am looking at the report and some numbers do not look right so I need to check the query to see if there was something written incorrectly in the code.

Is there anyway in some logs maybe where I might be able to see the code for the query I ran (and did not save) back in June? This would be AWSOME if I can. Thanks!

Best Answer

If your SQL Server has not been restarted there may a chance that your query text might have have been cached along with its execution plan. You may want to run the following to see if query text is still in the plan.

SELECT 
    cp.objtype AS ObjectType,
    OBJECT_NAME(st.objectid,st.dbid) AS ObjectName,
    cp.usecounts AS ExecutionCount,
    st.TEXT AS QueryText,
    qp.query_plan AS QueryPlan
FROM 
    sys.dm_exec_cached_plans AS cp 
CROSS APPLY 
    sys.dm_exec_query_plan(cp.plan_handle) AS qp 
CROSS APPLY 
    sys.dm_exec_sql_text(cp.plan_handle) AS st 
WHERE 
    st.text LIKE  '%query search criteria%'