SQL Server Datepart之间,下一个' x'天

时间:2014-11-13 06:10:07

标签: sql-server between dateadd

我正在尝试找出在接下来的5天内查看到期订单的最佳方式

如果我输入-10而不是+10,我的代码就有效,所以我对我的错误感到有些困惑

EG,我过去10天的代码工作正常

select  
    PurchaseOrder, OrderDueDate
from 
    PorMasterHdr
where 
    OrderDueDate between DATEADD(day, datediff(DAY, 0, GETDATE()) -10, 0)
                     and DATEADD(day, datediff(day, 0, GETDATE()),  0) 
order by 
    OrderDueDate desc

但在接下来的10天内,返回0行 - 肯定会在未来10天内到期的项目

select  
    PurchaseOrder, OrderDueDate 
from  
    PorMasterHdr
where 
    OrderDueDate between DATEADD(day, datediff(DAY, 0, GETDATE()) +10, 0)
                     and DATEADD(day, datediff(day, 0, GETDATE()),  0) 
order by 
    OrderDueDate desc

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您应该在开始/结束表达式之间切换。

代码应如下所示:

select  PurchaseOrder, OrderDueDate 
from PorMasterHdr
where OrderDueDate between
DATEADD (day,datediff(DAY,0,GETDATE()), 0)
AND
dateadd(day,datediff(day, 0 ,getdate()) +10,  0) 
order by OrderDueDate desc

答案 1 :(得分:0)

应该首先是最短的日期,即" 2014-11-01'和' 2014-11-10' "是正确的  和 "在2014-11-10之间'和' 2014-11-01"是错的

所以你的查询是:

select 
    PurchaseOrder, OrderDueDate 
from 
    PorMasterHdr 
where 
    OrderDueDate between dateadd(day, datediff(day, 0, getdate()), 0) 
                     and dateadd(day, datediff(DAY, 0, GETDATE()) +10, 0)
order by 
    OrderDueDate desc