Home Forums SQL Server 2012 SQL 2012 - General Select statement based on getdate() depending on time of day RE: Select statement based on getdate() depending on time of day

  • delacruz.ald - Wednesday, April 25, 2018 1:56 PM

    For anyone that may need something like this in the future. Here's the code I came up with.SELECT ActualW, LineDate, NewDate, Description, MinusTolerance, PlusTolerance, TargetW, LineTimeFROM dbo.line4NewdateWHERE (NewDate >= CASE WHEN datepart(hh, getdate()) < 15 THEN dateadd(hh, - 9, dateadd(dd, datediff(dd, 0, getdate()), 0)) ELSE dateadd(hh, 15, dateadd(dd, datediff(dd, 0, getdate()), 0)) END) AND (NewDate < CASE WHEN datepart(hh, getdate()) < 15 THEN dateadd(hh, 3, dateadd(dd, datediff(dd, 0, getdate()), 0)) ELSE dateadd(hh, 27, dateadd(dd, datediff(dd, 0, getdate()), 0)) END)It's not fully tested, I'll have to change the date to midnight to make sure it works.

    Looks to me like the code I posted does the same thing without using a CASE clause:

    SELECT
        [ActualW]
        , [LineDate]
        , [NewDate]
        , [Description]
        , [MinusTolerance]
        , [PlusTolerance]
        , [TargetW]
        , [LineTime]
    FROM
        [dbo].[line4Newdate]
    WHERE
        ([NewDate]     >= DATEADD(HOUR, 15, DATEADD(DAY,DATEDIFF(DAY,0,DATEADD(HOUR, -15, GETDATE())),0)))
        AND ([NewDate] < DATEADD(HOUR, 12, DATEADD(HOUR, 15, DATEADD(DAY,DATEDIFF(DAY,0,DATEADD(HOUR, -15, GETDATE())),0))));