Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to find the last day of the month in 6 months time

I am trying to write a bit of SQL that will give the last day of the month in 6 months time.

E.g. if I have of a date of inspection 15-07-2015 I want the next inspection date to be 31-01-2016

The date of inspection could be any day of any month

Any advise would be appreciated.

like image 531
Joe M Avatar asked Jan 08 '23 13:01

Joe M


2 Answers

if i understand. that's it

declare @d date = '2015-07-15'
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@d)+7,0))
like image 199
Mattia Caputo Avatar answered Mar 04 '23 09:03

Mattia Caputo


If you are using SQL Server 2012+ you can use the eomonth function to get the last day of a month:

declare @d date = '2015-07-15'
select eomonth(@d,6)

result: 2016-01-31

The function takes a date and an optional integer that specifies the number of months to add to the date parameter.

like image 45
jpw Avatar answered Mar 04 '23 07:03

jpw