Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain SQL Server executed query history of specific database

Tags:

sql

sql-server

Is there a mechanism to obtain a history of queries executed on a specific database in SQL Server 2012? I tried with below method, but it provides the entire history of the SQL Server.

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

Results:

enter image description here

like image 540
cs-87 Avatar asked Oct 26 '25 07:10

cs-87


1 Answers

You can achieve it in this way

Where dbid = (Select database_id from sys.databases Where name = 'your_database_name')

Full query:

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
Where dbid = (select database_id from sys.databases Where name = 'your_database_name')
ORDER BY deqs.last_execution_time DESC 
like image 159
Nguyễn Văn Phong Avatar answered Oct 28 '25 23:10

Nguyễn Văn Phong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!