如何查询特定时间范围以外的特定日期范围

时间:2012-08-09 17:08:27

标签: sql sql-server vb.net datetime

我有一个用Windows调度程序自动运行的程序。程序执行的操作是运行查询“昨天”结果...然后过滤结果,不包括特定时间范围内的任何内容。我现在遇到的问题是我必须在查询中指定日期...如何让查询自动排除时间(早上5:30到早上6:15)

SELECT  Store_Id, DM_Corp_Received_Date
FROM    Register_Till_Count_Tb
WHERE   (DM_Corp_Received_Date >= DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1, 0)) 
    AND (Register_Transaction_Type = 'sod') 
    AND (DM_Corp_Received_Date < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) 
    AND (DM_Corp_Received_Date NOT BETWEEN CONVERT(datetime, '2012-08-08 05:30:00', 102) AND CONVERT(Datetime, '2012-08-08 06:15:00', 102))

1 个答案:

答案 0 :(得分:1)

DECLARE @Yesterday DATETIME = DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1, 0));
DECLARE @Today DATETIME = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0));

SELECT  Store_Id, DM_Corp_Received_Date
FROM    Register_Till_Count_Tb
WHERE   (DM_Corp_Received_Date >= @Yesterday
    AND (Register_Transaction_Type = 'sod') 
    AND (DM_Corp_Received_Date < @Today
    AND (DM_Corp_Received_Date NOT BETWEEN DATEADD(minute, 5*60+30, @Yesterday) AND   
         DATEADD(minute, 6*60+15, @Yesterday))

请注意BETWEEN是包容性的,因此要小心你的界限。