DECLARE @P0 nvarchar(4000),@P1 nvarchar(4000); SET @P0='1';SET @P1='K172'; SELECT [recid],[machine_no] ,[stop_stime] ,[stop_etime] ,[status] ,[memo] ,[createddate] FROM machine_stop_alarm_msg t WHERE 1=1 AND t.status=@P0 AND t.machine_no in(@P1 ) ORDER BY machine_no, stop_stime ;
CREATE NONCLUSTERED INDEX ix_machine_stop_alarm_msg_n1ON [dbo].[machine_stop_alarm_msg] ([machine_no],[status])INCLUDE ([recid],[stop_stime],[stop_etime],[memo],[createddate])GO
在测试环境测试时,我们先不增加这个索引,就出现了下面一个场景,两者都是走聚集索引扫描:
1: 执行计划走聚集索引扫描(Cluster Index Scan)
SET STATISTICS IO ON;SET STATISTICS TIME ON;DECLARE @P0 nvarchar(4000),@P1 nvarchar(4000); SET @P0='1';SET @P1='K172';SELECT [recid],[machine_no] ,[stop_stime] ,[stop_etime] ,[status] ,[memo] ,[createddate] FROM machine_stop_alarm_msg t WHERE 1=1 AND t.status=@P0 AND t.machine_no in(@P1 ) ORDER BY machine_no, stop_stime ; SET STATISTICS IO OFF;SET STATISTICS TIME OFF;
2: 执行计划走聚集索引扫描(Cluster Index Scan)
SET STATISTICS IO ON;SET STATISTICS TIME ON;DECLARE @P0 VARCHAR(10),@P1 VARCHAR(10); SET @P0='1';SET @P1='K172';SELECT [recid],[machine_no] ,[stop_stime] ,[stop_etime] ,[status] ,[memo] ,[createddate] FROM machine_stop_alarm_msg t WHERE 1=1 AND t.status=@P0 AND t.machine_no in(@P1 ) ORDER BY machine_no, stop_stime ; SET STATISTICS IO OFF;SET STATISTICS TIME OFF;
上面发生隐式转换的SQL的执行计划,多了一个常量扫描(Constant Scan),常量扫描做的工作是根据用户输入的SQL中的常量生成一个行 ,MSDN的介绍如下:
"The Constant Scan operator introduces one or more constant rows into a query. A Compute Scalar operator is often used after a Constant
Scan to add columns to a row produced by the Constant Scan operator"