查询历史是否存储在一些日志文件中?如果有,你能告诉我怎么找到他们的位置吗?如果没有,你能给我一些建议吗?


当前回答

下面的SQL查询可以显示简单的查询日志:

SELECT last_execution_time, text
FROM sys.dm_exec_query_stats stats
CROSS APPLY sys.dm_exec_sql_text(stats.sql_handle) 
ORDER BY last_execution_time

下图是它的样子:

并且,下面的SQL查询可以显示简单的事务查询日志:

SELECT Operation, [Begin Time], [End Time] 
FROM fn_dblog(NULL,NULL)

下图是它的样子:

此外,我还不知道SQL查询将简单查询日志和简单事务查询日志显示在一起。

其他回答

If the queries you are interested in are dynamic queries that fail intermittently, you could log the SQL and the datetime and user in a table at the time the dynamic statement is created. It would be done on a case-by case basis though as it requires specific programming to happen and it takes a littel extra processing time, so do it only for those few queries you are most concerned about. But having a log of the specific statements executed can really help when you are trying to find out why it fails once a month only. Dynamic queries are hard to thoroughly test and sometimes you get one specific input value that just won't work and doing this logging at the time the SQL is created is often the best way to see what specifically wasn in the sql that was built.

你可以使用“每次保存自动生成脚本”,如果你使用管理工作室。 这当然不是日志。 检查一下是否对你有用。;)

系统不会以这种方式记录查询。如果你知道你想提前这么做,你可以使用SQL Profiler来记录将要输入的内容,并在Profiler运行期间跟踪查询。

晚一点,但希望有用,因为它增加了更多的细节…

在默认情况下,无法查看在SSMS中执行的查询。不过也有几种选择。

读取事务日志-这不是一件容易的事情,因为它是私有格式。但是,如果您需要查看历史上执行的查询(除了SELECT),这是唯一的方法。

您可以使用第三方工具,如ApexSQL日志和SQL日志救援(免费,但仅限SQL 2000)。查看这个线程的更多细节在这里SQL Server事务日志资源管理器/分析器

SQL Server分析器-最适合如果你只是想开始审计,你不感兴趣之前发生了什么。确保使用筛选器只选择您需要的事务。否则你很快就会得到大量的数据。

SQL Server跟踪—如果您想捕获所有或大部分命令,并将它们保存在跟踪文件中,以便稍后进行解析,则最适合。

触发器—如果您想捕获DML(除了select)并将它们存储在数据库中的某个地方,那么最适合使用它

我相信在座各位的回答。

这个脚本展示了如何找到影响SQL的最慢的20个查询

select top 20 dest.text, deqs.execution_count, deqs.total_elapsed_time, deqs.total_worker_time,
(deqs.total_elapsed_time / deqs.execution_count) as 'avg_elapse_time',
(deqs.total_worker_time / deqs.execution_count) as 'avg_worker_time'
from sys.dm_exec_query_stats as deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) as dest
where deqs. last_execution_time >= '2021-09-27 16:00' /* YOUR DATE AND TIME HERE*/
order by 'avg_elapse_time' desc