如何摆脱执行计划中的排序?

时间:2017-12-05 22:32:18

标签: sql-server sorting query-optimization

我正在写一个函数,它返回两个给定日期之间所有N个工作日。

create table dbo.tCalendar (
      [Date] date not null primary key
    , DayOff bit  not null
);
go
create nonclustered index X_tCalendar_Date_DayOff on dbo.tCalendar ([Date], DayOff);
go
insert into dbo.tCalendar ([Date], DayOff) values
 ('2017-10-01', 1),('2017-10-02', 0),('2017-10-03', 0),('2017-10-04', 0)
,('2017-10-05', 0),('2017-10-06', 0),('2017-10-07', 1),('2017-10-08', 1)
,('2017-10-09', 0),('2017-10-10', 0),('2017-10-11', 0),('2017-10-12', 0)
,('2017-10-13', 0),('2017-10-14', 1),('2017-10-15', 1),('2017-10-16', 0)
,('2017-10-17', 0),('2017-10-18', 0),('2017-10-19', 0),('2017-10-20', 0)
,('2017-10-21', 1),('2017-10-22', 1),('2017-10-23', 0),('2017-10-24', 0)
,('2017-10-25', 0),('2017-10-26', 0),('2017-10-27', 0),('2017-10-28', 1)
,('2017-10-29', 1),('2017-10-30', 0),('2017-10-31', 0),('2017-11-01', 0)
,('2017-11-02', 0),('2017-11-03', 0),('2017-11-04', 1),('2017-11-05', 1)
,('2017-11-06', 0),('2017-11-07', 0),('2017-11-08', 0),('2017-11-09', 0)
,('2017-11-10', 0),('2017-11-11', 1),('2017-11-12', 1),('2017-11-13', 0)
,('2017-11-14', 0),('2017-11-15', 0),('2017-11-16', 0),('2017-11-17', 0)
,('2017-11-18', 1),('2017-11-19', 1),('2017-11-20', 0),('2017-11-21', 0)
,('2017-11-22', 0),('2017-11-23', 0),('2017-11-24', 0),('2017-11-25', 1)
,('2017-11-26', 1),('2017-11-27', 0),('2017-11-28', 0),('2017-11-29', 0)
,('2017-11-30', 0)
go

declare
      @dtDateFrom  date = '2017-10-03' -- first date of interval
    , @dtDateTo    date = '2017-11-25' -- last date of interval
    , @nNumWorkDay int = 10 -- number of working day of the month

select [Date]
from (
    select [Date], row_number() over(partition by convert (varchar(6), [Date], 112) order by [Date]) as num
    from (
        select [Date]
        from dbo.tCalendar
        where [Date] between dateadd (dd, 1, eomonth (@dtDateFrom, -1)) and @dtDateTo
            and DayOff = 0
    ) t
) t
where num = @nNumWorkDay
    and [Date] >= @dtDateFrom
go

if object_id ('dbo.tCalendar') is not null drop table dbo.tCalendar;

结果集:

Date
----------
2017-10-13
2017-11-14

这是查询计划: enter image description here

我担心第3步的查询计划中的排序操作?

convert (varchar(6), [Date], 112)[Date]排序。

但实际上没有必要使用sort,而index返回已正确排序的数据。

是否有可能摆脱排序?

0 个答案:

没有答案
相关问题