时间:2021-07-01 10:21:17 帮助过:45人阅读
索引的创建时间
索引的创建时间,可以用下面SQL获取,但是我们知道跟踪有可能停止或禁用;跟踪文件也可能被覆盖。所以这种方法只能查询最近一段时间的。它有很强的时效性。所以这种方法不能通用。注定其只能作为一种方法参考,而不能通用。
DECLARE @filename VARCHAR(500)
SELECT @filename = CAST(value AS VARCHAR(500))
FROM fn_trace_getinfo(DEFAULT)
WHERE property = 2
AND value IS NOT NULL
-- Go back 4 files since default trace only keeps the last 5 and start from there.
SELECT @filename = substring(@filename, 0, charindex(‘_‘, @filename)+1) + convert(varchar, (convert(int, substring(left(@filename, len(@filename)-4), charindex(‘_‘, @filename)+1, len(@filename)))-4)) + ‘.trc‘
SELECT
gt.EventClass,
gt.EventSubClass,
te.Name AS EventName,
gt.HostName,
gt.StartTime,
gt.DatabaseName,
gt.ObjectName,
gt.IndexID
FROM fn_trace_gettable(@fileName, DEFAULT) gt
JOIN sys.trace_events te ON gt.EventClass = te.trace_event_id
WHERE EventClass = 46
and ObjectType = 22601
and gt.DatabaseName <> ‘tempdb‘
ORDER BY StartTime desc;
索引的重建时间 &索引的重组时间
如下所示,Object:Altered的trace_event_id为164,这里我们无法区分ALTER INDEX ... REBUILD 和 ALETER INDEX ...REORGANIZE. 对于索引重建、索引重组,fn_trace_gettable返回的TextData为Null值,也无从判断。所以这里能记录准确的时间,但是无法区分索引重建与索引重组。
DECLARE @filename VARCHAR(500)
SELECT @filename = CAST(value AS VARCHAR(500))
FROM fn_trace_getinfo(DEFAULT)
WHERE property = 2
AND value IS NOT NULL
-- Go back 4 files since default trace only keeps the last 5 and start from there.
SELECT @filename = substring(@filename, 0, charindex(‘_‘, @filename)+1) + convert(varchar, (convert(int, substring(left(@filename, len(@filename)-4), charindex(‘_‘, @filename)+1, len(@filename)))-4)) + ‘.trc‘
SELECT
gt.EventClass,
gt.EventSubClass,
te.Name AS EventName,
gt.HostName,
gt.StartTime,
gt.DatabaseName,
gt.ObjectName,
gt.IndexID
FROM fn_trace_gettable(@fileName, DEFAULT) gt
JOIN sys.trace_events te ON gt.EventClass = te.trace_event_id
WHERE EventClass = 164
and ObjectType = 22601
and gt.DatabaseName <> ‘tempdb‘
ORDER BY StartTime desc;
测试验证如下所示:
USE YourSQLDba;
GO
ALTER INDEX Pk_HistMaintTrav ON [Maint].[JobHistory] REBUILD;
ALTER INDEX PK_DataBaseSizeDtl_Day ON [Maint].[DataBaseSizeDtl_Day] REORGANIZE;
CREATE INDEX IX_DataBaseSizeDtl_Day_N1 ON [Maint].[DataBaseSizeDtl_Day](DataBaseName);
注意:上面脚本在有些环境可能会出错,主要是因为trac文件的路径,例如C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Log\log_603.trc 就会遇到下面错误,需要根据实际情况修改脚本。
Msg 245, Level 16, State 1, Line 8
Conversion failed when converting the varchar value ‘50.MSSQLSERVER\MSSQL\Log\log_603‘ to data type int.
参考资料:
https://sqlconjuror.com/sql-server-get-index-creation-date/
SQL Server获取索引创建时间&重建时间&重组时间
标签:word ldb com sqlserver use padding cas 验证 sub