Recover unsaved SQL query scripts

BumbleBee picture BumbleBee · Feb 23, 2013 · Viewed 274.9k times · Source

How to recover the unsaved scripts if the SSMS crashes / unsaved tab gets accidentally closed?

Answer

BumbleBee picture BumbleBee · Feb 23, 2013

Posting this in case if somebody stumbles into same problem.

Googled for Retrieve unsaved Scripts and found a solution.

Run the following select script. It provides a list of scripts and its time of execution in the last 24 hours. This will be helpful to retrieve the scripts, if we close our query window in SQL Server management studio without saving the script. It works for all executed scripts not only a view or procedure.

Use <database>
SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script] FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC