Query - Last Executed queries on sql server

Below
query give us list of queries which was executed on sql server, need to filter out by
database id.



In
result set you will get plan_handle as well.



SELECT



 cp.plan_handle,



 cp.objtype,



 cp.usecounts,



 DB_NAME(st.dbid) AS [DatabaseName],



 [text]



FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st



WHERE dbid=5 ---pass Database Id here



order by cp.usecounts


Executed queries

SELECT Top 10
    ST.TEXT AS [SQLText],
    S.EXECUTION_COUNT [TimesExecuted],
    S.LAST_EXECUTION_TIME AS [LastTime], 
    DB_NAME(ST.dbid) AS [Database]
FROM
    SYS.DM_EXEC_QUERY_STATS AS S
    CROSS APPLY SYS.DM_EXEC_SQL_TEXT(S.SQL_HANDLE) AS ST
WHERE
    ST.dbid = DB_ID('SwarajInv')        -----------Database name here
--AND ST.TEXT like '%VisitDiagnosis%' -----------Search String - Query Text
ORDER BY S.LAST_EXECUTION_TIME DESC

Comments