在SQL Server中重建索引(Rebuild Index)與重組索引(Reorganize Index)會觸發統計資訊更新嗎? 那么我們先來測驗、驗證一下:
我們以AdventureWorks2014為測驗環境,如下所示:
Person.Person表的統計資訊最后一次更新為2014-07-17 16:11:31,如下截圖所示:
DECLARE @table_name NVARCHAR(32);SET @table_name='Person.Person'
SELECT sch.name + '.' + so.name AS table_name
, so.object_id
, ss.name AS stat_name, ds.stats_id
, ds.last_updated
, ds.rows, ds.rows_sampled
, ds.rows_sampled*1.0/ds.rows *100 AS sample_rate
, ds.steps
, ds.unfiltered_rows
--, ds.persisted_sample_percent
, ds.modification_counter
, 'UPDATE STATISTICS ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(sch.name) + '.' + QUOTENAME( so.name) + ' "' + RTRIM(LTRIM(ss.name)) + '" WITH SAMPLE 80 PERCENT;'
AS update_stat_scriptFROM sys.stats ssJOIN sys.objects so ON ss.object_id = so.object_id
JOIN sys.schemas sch ON so.schema_id = sch.schema_id
CROSS APPLY sys.dm_db_stats_properties(ss.object_id,ss.stats_id) dsWHERE so.is_ms_shipped = 0 AND so.object_id NOT IN (
SELECT major_id FROM sys.extended_properties (NOLOCK)WHERE name = N'microsoft_database_tools_support' )
AND so.object_id =OBJECT_ID(@table_name)

ALTER INDEX IX_Person_LastName_FirstName_MiddleName ON Person.Person REORGANIZE;
ALTER INDEX PK_Person_BusinessEntityID ON Person.Person REORGANIZE;
重組索引(Reorganize Index)后,驗證發現,索引重組不會觸發索引對應的統計資訊更新,驗證發現其不會觸發任何統計資訊更新,

結論:重組索引(Reorganize Index)不會觸發對應索引的統計資訊更新. 也不會觸發其它統計資訊更新,也就說,重組索引(Reorganize Index)不會觸發任何統計資訊更新,
那么重建索引(Rebuild Index)會更新對應的統計資訊嗎? 你可以測驗、驗證一下:如下所示,索引重建后,索引對應的統計資訊更新了,
ALTER INDEX PK_Person_BusinessEntityID ON Person.Person REBUILD;

結論:重建索引(Rebuild Index)會觸發對應索引的統計資訊更新,但是,重建索引(Rebuild Index)不會觸發其它統計資訊更新,
重建索引會觸發對應索引的統計資訊更新,那么統計資訊更新的采樣比例是多少? 根據測驗驗證,采樣比例為100%,如上截圖所示,也就說索引重建使用WITH FULLSCAN更新索引統計資訊. 如果表是磁區表呢?磁區表的磁區索引使用默認采樣演算法(default sampling rate),對于這個默認采樣演算法,沒有找到詳細的官方資料,
官方檔案:https://docs.microsoft.com/zh-cn/sql/relational-databases/partitions/partitioned-tables-and-indexes?view=sql-server-ver15里面有簡單介紹:
已磁區索引操作期間統計資訊計算中的行為更改
從SQL Server 2012 (11.x)開始,當創建或重新生成已磁區索引時,不會通過掃描表中的所有行來創建統計資訊, 相反,查詢優化器使用默認采樣演算法來生成統計資訊, 在升級具有已磁區索引的資料庫后,您可以在直方圖資料中注意到針對這些索引的差異, 此行為更改可能不會影響查詢性能, 若要通過掃描表中所有行的方法獲得有關已磁區索引的統計資訊,請使用 CREATE STATISTICS 或 UPDATE STATISTICS 以及 FULLSCAN 子句,
Starting with SQL Server 2012 (11.x), statistics are not created by scanning all the rows in the table when a partitioned index is created or rebuilt. Instead, the query optimizer uses the default sampling algorithm to generate statistics. After upgrading a database with partitioned indexes, you may notice a difference in the histogram data for these indexes. This change in behavior may not affect query performance. To obtain statistics on partitioned indexes by scanning all the rows in the table, use CREATE STATISTICS or UPDATE STATISTICS with the FULLSCAN clause.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/34243.html
標籤:SQL Server
上一篇:RMAN命令詳解和常用匯總
