<h2>Retrieve unsaved SQL query Scripts</h2>
<p>It was a pleasant day; I am querying a confused SQL script which is not a stored procedure or Views. Unexpectedly I close the window without saving the script.<br />
<br />
I strained out and upset, because I am working on it for past 2 hours. On seeing me my team mate asked what is the problem, I screamed to her about my nonsense activity. <br />
<br />
She gave me a query to run to retrieve my query. It work fine and I am so happy.<br />
<br />
Also I got the message for tip of the day to post and share with you.<br />
<br />
Run the following select script. It provides a list of scripts and its time of execution in the last 24 hours. <br />
<br />
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.<br />
 </p>
<pre name="code" class="sql">
Use Master
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</pre>