Home > Back-end >  How to select data using getdate() time?
How to select data using getdate() time?

Time:01-30

I have this code:

select * 
from Table
where [Date] >= cast(getdate() - 1 as date) 
  and [Date] < cast(getdate()   1 as date)
order by [Date] desc

and I need to change this part:

where [Date] >= cast(getdate() - 1 as date)

that the search start at 02:00 AM getdate() - 1,

Something like this:

where [Date] >= getdate() - 1, 02:00:00

CodePudding user response:

In SQL Server with the datetime type you can simply concatenate the time portion after first removing it. Try

where [Date] > DateAdd(dd, DateDiff(dd, 1, GetDate()), 0)   '02:00:00'

CodePudding user response:

where [Date] >=cast(concat(cast(DATEADD(day, -1, CAST(GETDATE() AS date)) as varchar(50)),' 02:00:00') as datetime)

CodePudding user response:

You can use some basic time arithmetic for this: subtract 22 hours, after stripping off the time

WHERE [Date] >= DATEADD(hour, -22, CAST(CAST(GETDATE() AS date) AS datetime))

You need to cast back to datetime otherwise you cannot add a time.

  •  Tags:  
  • Related