Question

Ok, I'm running query builder out of visual studio 2008. I'm trying to filter the results of the query by time; that is, I want to pull everything from the start of yesterday to noon yesterday. I've been using GETDATE()-1 for yesterday, which pulls up a timestamp mm/dd/yyyy hh:mm:ss however, it pulls the current time. to get it to run from the start of the day I appended the timestamp to remove the time itself, so it started at the beginning of the day:

convert(varchar(10), getdate()-1, 120)

so I'm using between to find the range, I have: BETWEEN convert(varchar(10), getdate()-1, 120) AND // this is where I need it to cut off at noon.

I'm understanding that datetime is a data type here, so I tried subtracting the hours/minutes/seconds using date part, but datepart() only returns ints and doesn't affect the time.

thoughts? how do I get this to cut off at noon

Was it helpful?

Solution 2

DECLARE
    @Min DATETIME
  , @Max DATETIME

SELECT
    @Min = DATEADD(DAY, -1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
  , @Max = DATEADD(HOUR, 12, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))

SELECT *
FROM <Table> x
WHERE x.[Date] BETWEEN @Min AND @Max

OTHER TIPS

Try this:

--Variables
declare @now datetime = getdate(),
        @yesterday datetime

--Yesterday starting datetime
select @yesterday = convert(datetime, convert(date, dateadd(day,-1,@now)))

--Your query to filter between y'day start and y'day noon
--Note that between means inclusive boundary values. (or use >= and <=)
select * from yourTable
where dateCol between @yesteray and dateadd(hour,12,@yesterday)
SELECT * FROM T WHERE YourDate BETWEEN CAST(GETDATE()-1 As DATE) AND DATEADD(Hour, -12, CAST(CAST(GETDATE() As DATE) As DATETIME) )

Beware because BETWEEN will include lower and upper boundaries, so you can simply replace BETWEEN with x >= y and y < z if you don't want yesterday at 12:00 to be taken in account

between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(getdate() as date))

Edit: As mentioned in the comments, you can't use hours with a date, you have to cast it back to a datetime, thus:

between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(cast(getdate() as date) as datetime))

If you want to get the results from last 30 mins you need to use this. You can change MINUTE to HOUR too.

--Get now, hour and second included    
DECLARE @NOW DATETIME = GETDATE() 

--Get 30 mins from now
DECLARE @TranDate DATETIME 
SET @TranDate = CONVERT(DATETIME, CONVERT(DATETIME, DATEADD(MINUTE,-30,@NOW))) 

After That, add below code to your where statement,

AND TK.TransactionDate >= @TranDate
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top