组合索引

只要你的查询 WHERE 里有 ≥2 个字段一起用来精确查找,
并且这条查询执行慢、经常被调用、数据量大,
那就应该建组合索引。

看是否出现以下性能症状(满足任意一条就该建)
·查询超时
·执行时间长
·SQL Server 执行计划显示 Table Scan / Clustered Index Scan(全表扫描)
·服务器 CPU 高、I/O 高
·相同条件查询忽快忽慢(因为数据膨胀)

Select id from JobHistory where lotid='' and waferid='' and time='***'

新建组合索引

USE Server_DB
GO

IF NOT EXISTS (
    SELECT * FROM sys.indexes 
    WHERE name = 'IX_JobHistory_LotWaferTimeRecipe' 
      AND object_id = OBJECT_ID('JobHistory')
)
BEGIN
    CREATE NONCLUSTERED INDEX IX_JobHistory_LotWaferTimeRecipe
    ON dbo.JobHistory (lotid, waferid, time, recipename)
    INCLUDE (id);
END

索引维护

检查表碎片

image
· 碎片 >30%:需要重建索引
· 碎片 5%~30%:重组索引

SELECT 
    OBJECT_NAME(ips.object_id) AS TableName,
    i.name AS IndexName,
    ips.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('JobHistory'), NULL, NULL, 'DETAILED') ips
JOIN sys.indexes i ON ips.object_id = i.object_id AND ips.index_id = i.index_id
ORDER BY avg_fragmentation_in_percent DESC;

重建重组

-- 重建索引(锁表,建议业务低峰执行)
ALTER INDEX IX_JobHistory_LotWaferTimeRecipe 
ON dbo.JobHistory REBUILD;

-- 或重组(不锁表)
ALTER INDEX IX_JobHistory_LotWaferTimeRecipe 
ON dbo.JobHistory REORGANIZE;

查看执行计划

image

SET SHOWPLAN_XML ON;
GO

Select id from JobHistory where lotid='***' and waferid='***' and time='***'

GO
SET SHOWPLAN_XML OFF;
posted @ 2026-08-04 18:11  wesson2019  阅读(7)  评论(0)    收藏  举报