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


当前回答

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

其他回答

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

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.

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

一个稍微开箱即用的方法是在AutoHotKey中编写一个解决方案。我用了这个,它不是完美的,但是有效而且免费。从本质上讲,这个脚本为CTRL+SHIFT+R分配了一个热键,它将复制SSMS (CTRL+C)中所选的SQL,保存一个日期戳SQL文件,然后执行突出显示的查询(F5)。如果您不习惯AHK脚本,则前导分号是注释。

;CTRL+SHIFT+R to run a query that is first saved off
^+r::
;Copy
Send, ^c
; Set variables
EnvGet, HomeDir, USERPROFILE
FormatTime, DateString,,yyyyMMdd
FormatTime, TimeString,,hhmmss
; Make a spot to save the clipboard
FileCreateDir %HomeDir%\Documents\sqlhist\%DateString%
FileAppend, %Clipboard%, %HomeDir%\Documents\sqlhist\%DateString%\%TimeString%.sql
; execute the query
Send, {f5}
Return

最大的限制是,如果你点击“执行”而不是使用键盘快捷键,这个脚本将无法工作,并且这个脚本不会保存整个文件-只保存选中的文本。但是,您总是可以修改脚本以执行查询,然后在复制/保存之前选择所有(CTRL+A)。

使用具有“在文件中查找”功能的现代编辑器可以让您搜索SQL历史记录。您甚至可以把您的文件刮到SQLite3数据库中以查询您的查询。

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

这将显示查询运行的时间和日期