WITH autostats(object_id, stats_id, name, column_id) AS ( SELECT sys.stats.object_id , sys.stats.stats_id , sys.stats.name , sys.stats_columns.column_id FROM sys.stats INNERJOIN sys.stats_columns ON sys.stats.object_id = sys.stats_columns.object_id AND sys.stats.stats_id = sys.stats_columns.stats_id WHERE sys.stats.auto_created =1 AND sys.stats_columns.stats_column_id =1 ) SELECT OBJECT_NAME(sys.stats.object_id) AS [Table] , sys.columns.name AS [Column] , sys.stats.name AS [Overlapped] , autostats.name AS [Overlapping] , 'DROP STATISTICS ['+ OBJECT_SCHEMA_NAME(sys.stats.object_id) +'].['+ OBJECT_NAME(sys.stats.object_id) +'].['+ autostats.name +']' FROM sys.stats INNERJOIN sys.stats_columns ON sys.stats.object_id = sys.stats_columns.object_id AND sys.stats.stats_id = sys.stats_columns.stats_id INNERJOIN autostats ON sys.stats_columns.object_id = autostats.object_id AND sys.stats_columns.column_id = autostats.column_id INNERJOIN sys.columns ON sys.stats.object_id = sys.columns.object_id AND sys.stats_columns.column_id = sys.columns.column_id WHERE sys.stats.auto_created =0 AND sys.stats_columns.stats_column_id =1 AND sys.stats_columns.stats_id != autostats.stats_id AND OBJECTPROPERTY(sys.stats.object_id, 'IsMsShipped') =0;
create table dbo.MemoryGrantDemo ( ID intnot null, Col intnot null, Placeholder char(8000) ); createunique clustered index IDX_MemoryGrantDemo_ID on dbo.MemoryGrantDemo(ID);
;with N1(C) as (select0unionallselect0) -- 2 rows ,N2(C) as (select0from N1 as T1 crossjoin N1 as T2) -- 4 rows ,N3(C) as (select0from N2 as T1 crossjoin N2 as T2) -- 16 rows ,N4(C) as (select0from N3 as T1 crossjoin N3 as T2) -- 256 rows ,N5(C) as (select0from N4 as T1 crossjoin N4 as T2) -- 65,536 rows ,IDs(ID) as (selectrow_number() over (orderby (selectnull)) from N5) insert into dbo.MemoryGrantDemo(ID,Col,Placeholder) select ID, ID %100, convert(char(100),ID) from IDs; create nonclustered index IDX_MemoryGrantDemo_Col on dbo.MemoryGrantDemo(Col);
建立一張表MemoryGrantDemo並建立Clustered Index跟新增65,536筆資料Col介於1~100之間,最後在建立一個NonClustered Index
Col介於1~100之間會有統計值
1 2 3 4 5 6 7 8 9 10
;with N1(C) as (select0unionallselect0) -- 2 rows ,N2(C) as (select0from N1 as T1 crossjoin N1 as T2) -- 4 rows ,N3(C) as (select0from N2 as T1 crossjoin N2 as T2) -- 16 rows ,N4(C) as (select0from N3 as T1 crossjoin N3 as T2) -- 256 rows ,N5(C) as (select0from N4 as T1 crossjoin N2 as T2) -- 1,024 rows ,IDs(ID) as (selectrow_number() over (orderby (selectnull)) from N5) insert into dbo.MemoryGrantDemo(ID,Col,Placeholder) select100000+ ID, 1000, convert(char(100),ID) from IDs where ID <=656;
最後在新增Col = 1000的656筆資料
因為只有新增656只有原本的1%所以不會觸法更新統計值
如下圖能看到IDX_MemoryGrantDemo_Col並沒有Col=1000的資訊
建立好資料後我們使用statistics和打開執行計畫來看看兩者差別
1 2 3 4 5 6 7
declare @Dummyint set statistics timeon select@Dummy= ID from dbo.MemoryGrantDemo where Col =1orderby Placeholder; select@Dummy= ID from dbo.MemoryGrantDemo where Col =1000orderby Placeholder; set statistics time off