Last executed queries for a specific database

Sql ServerSql Server-2012

Sql Server Problem Overview


I know how to get the last executed queries using the following SQL in SSMS -

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC

But I want to find them for a specific database. I don't want to use SQL Profiler, if I don't have to. Plus I don't think SQL Profiler will allow me to view queries that were already run without profiling turned on. I need to do this from SSMS.

Sql Server Solutions


Solution 1 - Sql Server

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Solution 2 - Sql Server

Following works perfectly for me : hope this helps

SELECT
    deqs.last_execution_time AS [Time], 
    dest.TEXT AS [Query]
 FROM 
    sys.dm_exec_query_stats AS deqs
    CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY 
    deqs.last_execution_time DESC

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMukusView Question on Stackoverflow
Solution 1 - Sql Servertommy_oView Answer on Stackoverflow
Solution 2 - Sql ServerJack GajananView Answer on Stackoverflow