Home > Software design >  T-SQL select date withing 30 days range
T-SQL select date withing 30 days range

Time:04-22

I would like to select all the rows with dates between 30 days range from today,

so between 22-04-2022 till 22-05-2022,

I've tried

SELECT DATEXP, ID FROM TABLE
where DATEXP > cast(getdate()   30 as date) and DATEXP <= cast(getdate() as date)

but this doesn't seem to do it

CodePudding user response:

You should use the DATEADD() function here:

SELECT DATEXP, ID
FROM yourTable
WHERE DATEXP >= GETDATE() AND DATEXP < DATEADD(day, 30, GETDATE());

Also note that your inequality was incorrect. You should have the earlier date on the left GTE comparison and the later date on the right LT comparison.

CodePudding user response:

Your condition seems to be wrong, you are expecting the date to be >= Today 30 days BUT less than today.

So if for example.

Today is 22 April 2022

Today 30 = 22 May 2022

If I have a date DATEXP say 23 May 2022, it can't be >= 22 May 2022 and LESS then 22 April 2022 at the same time.

Maybe you want the Condition to be >= Today AND < Today 30?

  • Related