In my table I have a Month(tinyint) and a Day(tinyint) field. I would like to have a function that takes this month and day and produces a datetime for the next date(including year) given this month and day.
So if I had Month = 9, Day = 7 it would produce 9/7/2009.
If I had Month 1, Day 1 it would produce 1/1/2010.
To get Next Month Date, pass the MONTH datepart to the DATEADD function followed by the number of months we want to add followed by the given date which is the registration date (RegDate) in our case.
For this purpose you can use the built-in function DATEFROMPARTS. This function was introduced in SQL Server 2012. This function accepts day, month and year values in integer and returns a date.
We can retrieve the current month value in SQL using the MONTH() and DATEPART() functions along with the GETDATE() function. To retrieve the name of the month functions in SQL such as DATENAME() and FORMAT() are used.
something like this would work. It's variation on your method, but it doesn't use the MM/DD/YYYY literal format, and it won't blowup against bad input (for better or for worse).
declare @month tinyint
declare @day tinyint
set @month = 9
set @day = 1
declare @date datetime
-- this could be inlined if desired
set @date = convert(char(4),year(getdate()))+'0101'
set @date = dateadd(month,@month-1,@date)
set @date = dateadd(day,@day-1,@date)
if @date <= getdate()-1
set @date = dateadd(year,1,@date)
select @date
Alternatively, to create a string in YYYYMMDD format:
set @date =
right('0000'+convert(char(4),year(getdate())),4)
+ right('00'+convert(char(2),@month),2)
+ right('00'+convert(char(2),@day),2)
Another method, which avoids literals all together:
declare @month tinyint
declare @day tinyint
set @month = 6
set @day = 24
declare @date datetime
declare @today datetime
-- get todays date, stripping out the hours and minutes
-- and save the value for later
set @date = floor(convert(float,getdate()))
set @today = @date
-- add the appropriate number of months and days
set @date = dateadd(month,@month-month(@date),@date)
set @date = dateadd(day,@day-day(@date),@date)
-- increment year by 1 if necessary
if @date < @today set @date = dateadd(year,1,@date)
select @date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With