Retrieve Unsaved SQL Query Scripts

Introduction

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

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

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

Fig.1 List of Unsaved Scripts

Conclusion

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:

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

Website Built with WordPress.com.

Up ↑

<span>%d</span> bloggers like this: