调优SQL思路

--调优SQL


--sqlreview ->logshipping -> ag辅助副本


--查看正确的执行计划 打开实际的执行计划
set statistics io on


--查看错误的执行计划 打开实际的执行计划
set statistics io on


--对比 正确和错误 执行计划的差别
紧盯最大返回记录数处,找最粗的,不要看cost百分比 没用!
找出问题点,是否走错了索引,或未走做引

--对于缺失索引的 创建索引
use SiccDB
sp_spaceused CDRSub_Current_Merge --116GB

create index idx_CDRSub_Merge_Truncated on CDRSub_Current_Merge(TIME_IN) with(online=on)


--对于走错的索引的 释放错误的执行计划
select sql_handle,* from sys.dm_exec_requests where session_id=77

DBCC FREEPROCCACHE (0x060006001ECA270EC0215D05000000000000000000000000);
GO


--更新索引统计信息
update statistics CDRSub_Current_Merge
update statistics CDRSub_Current_Merge idx_CDRSub_Merge_Truncated


--再次运行sql,查看是否正常

--更新统计信息无效,查看索引碎片率的情况
更新过统计信息后 实际返回行和评估返回行 还是有差距的话,需要查看索引是否碎片严重

SELECT avg_fragmentation_in_percent,* FROM sys.dm_db_index_physical_stats
(DB_ID(N'SiccDB'), OBJECT_ID(N'dbo.CDRSub_Current_Merge'), NULL, NULL , 'LIMITED');



use SiccDB
go
ALTER INDEX [idx_CDRSub_Merge_Truncated] on [dbo].[CDRSub_Current_Merge] rebuild WITH( ONLINE = ON ) --重建索引
ALTER INDEX [idx_anino] on [dbo].[CDRSub_Current_Merge] rebuild WITH( ONLINE = ON )
ALTER INDEX [idx_dnisno] on [dbo].[CDRSub_Current_Merge] rebuild WITH( ONLINE = ON )

--删除走错的索引,不推荐
exec configdb..spm_index_usages 'SiccDB','CDRSub_Current_Merge' --查看走错的索引最后一次使用时间,判断是否为无效索引! 对于无效索引 可以删除!


use SiccDB
go
DROP INDEX [idx_anino] ON [dbo].[CDRSub_Current_Merge]

--最后使用临时表
修改写法,采用临时表,按正常的执行计划顺序,一步步落数

注意:临时表会造成tempdb的page latch争用,并发量大的语句不推荐使用临时表

原文地址:https://www.cnblogs.com/justdba/p/5822303.html