Jan Kees
Jan Kees

Reputation: 195

T-SQL select date withing 30 days range

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

Upvotes: 0

Views: 931

Answers (2)

Dawood Awan
Dawood Awan

Reputation: 7318

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?

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

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.

Upvotes: 1

Related Questions