Friday 27 April 2018

Recover Unsaved SQL Query Scripts

If accidentally ssms is closed and you lost the script, or to retrieve previous 24 hours executed scripts, then below script will be helpful.

SELECT execquery.last_execution_time AS ExecutionDateTime, execsql.text AS QueryScript 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

For the older scripts, you may get the recovery files from the below location :

C:\Documents and Settings\Username\My Documents\SQL Server Management Studio\Backup Files\


Reference: Govind Badkur(http://sqlserver20.blogspot.com)