1

I'm looking to use either the IF/ELSE or the CASE functions to write a specific code. I'm wanting to have it check a column named DATEMODIFIED and see what hour it is. So basically I'm wanting to grab data from the hours of 1800 to 0600 the next morning. I was going to use the WHERE (Datemodified BETWEEN DATEADD(hour, - 12, GETDATE()) AND DATEADD(day, 0, GETDATE())) but that will go back 12 hours when when the query is ran. I don't want it to pull data past 1800 hours. So say its ran at 2200 hours, I want it to look back 4 hours and run a specific query. If it's ran at say 0200 the next morning, I want it to only look back 8 hours. I was messing around with the IF/ELSE and was unsuccessful.

Here is the query I've been using, but like I said, it pulls info way beyond 1800 hours depending on when it's ran. This query is designed only to be running at 6am in the morning, which will grab back 12 hours of data(1800-0600 hrs). Please help if you can! Thanks all!!

SELECT Assignment
, Datemodified
, General
, IncNumber
, NextSteps
, PDCRStatus
, RootCause
, Status
, Summary
, Timings
, UserID 
FROM Turnover 
WHERE (Datemodified BETWEEN DATEADD(hour, - 12, GETDATE()) AND DATEADD(day, 0, GETDATE()))
4

2 回答 2

1
Create Function dbo.PreviousDateHour (@RefDate as datetime, @Hour as int) Returns DateTime As
Begin
    Declare @ret datetime = null
    If @Hour Is Not Null And @RefDate Is Not Null
    Begin
        Set @ret = DateAdd(Day, DateDiff(Day, 0, @RefDate), 0) -- truncate to 00:00:00
        Set @ret = DateAdd(Hour, @Hour, @ret) -- Set correct hours
        If @ret > @RefDate
            Set @ret = DateAdd(Day, -1, @ret)
    End

    Return @ret
End

然后使用dbo.PreviousDateHour(GetDate(), 18)获取您想要的日期。

示例:http ://sqlfiddle.com/#!3/b264d/1

如果您使用的是 SQL 2012,那么DateTimeFromParts可能会使函数更简单。

于 2012-11-12T13:42:19.133 回答
0
select ... from Turnover
where Datemodified between 
dateadd(day, datediff(day, 0,dateadd(hour, -18, getdate())), '1900-01-01 18:00')
and dateadd(day, datediff(day, 0,dateadd(hour, -18, getdate())), '1900-01-02 06:00')
于 2012-11-12T14:10:44.183 回答