Retrieve Unsaved SQL Query Scripts


In this article, we will have a look how to retrieve the Unsaved SQL Query using T-SQL. Sometimes, we may close the Query Window or SSMS accidentally without saving. This may cause to loss the Queries which we where working.

Retrieve Unsaved SQL Query using T-SQL Statement

Apply the below T-SQL Statement in which DB we want to retrieve the unsaved queries. It provides a list of scripts and its time of execution in the last 24 hours

	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

When the above statement is executed, we will get the Output as shown below,

Fig.1 List of Unsaved Scripts


In this article, I have shared a simple tip to retrieve the unsaved scripts in SQL Server using T-SQL. I hope this article helped you to know something new. Please share your feedback in the comment section.

Consider reading other SQL articles of Mine

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Built with

Up ↑

%d bloggers like this: