venkat venkat - 4 months ago 9
SQL Question

sql query for next 4 month displaying

I want to print next four months data from sql server

column_name
2016-10-31
2016-07-31
2016-08-31
2016-09-30
2017-10-31
2015-07-31
2019-08-31
2017-09-30
2016-11-30


I want to output like this

2016-10-31
2016-08-31
2016-09-30
2016-11-30


Current query:

SELECT relieve_date
FROM table
WHERE DATEPART(m, relieve_date) = DATEPART(m, DATEADD(m, +4, getdate())) AND DATEPART(yyyy, relieve_date) = DATEPART(yyyy, DATEADD(m, -1, getdate()))

Answer

Your query is close, but needs a range (<=,>=) instead of =. You also won't need the year section if you use DATEADD:

SELECT relieve_date 
FROM   table 
WHERE  relieve_date >= DATEADD(month, 1, getdate())
AND    relieve_date <= DATEADD(month, 4, getdate())

Another option is BETWEEN, which uses (<=,>=) logic too:

SELECT relieve_date 
FROM   table 
WHERE  relieve_date BETWEEN DATEADD(month, 1, getdate()) AND DATEADD(month, 4, getdate())