Sql-server – How to do two date calculations in one SQL Statement

sql serversql-server-2008-r2

In a SQL Stored Procedure, I need to calculate a date by subtracting 1 month and set the day to the 17th of the month.

I can subtract 1 month with:

DATEADD(month,-1, loanFirstPmtDate)

But do not know how to also set the day to 17.

How do I do both calculations in one SQL statement?

Example: Loan First Payment Date = ‘03/01/2019’
Subtract 1 month and set day to 17 = ‘02/17/2019’

Best Answer

Given a date:

DECLARE @date datetime = CONVERT(date, GETDATE());

--The beginning of this month:

SELECT DATEADD(DAY, 1-DAY(GETDATE()), @date);

-- The beginning of last month - just subtract a month:

SELECT DATEADD(MONTH, -1, 
  DATEADD(DAY, 1-DAY(GETDATE()), @date));

-- Then to get the 17th of last month, just add 16 days:

SELECT DATEADD(DAY, 16, DATEADD(MONTH, -1, 
  DATEADD(DAY, 1-DAY(GETDATE()), @date)));

That will work on 2008 and above. On 2012 you can write it a little shorter:

DECLARE @date datetime = DATEADD(MONTH, -1, GETDATE());

SELECT DATEFROMPARTS(YEAR(@date), MONTH(@date), 17);

If you are doing this for searching, though, and not output, I highly recommend adjusting the date range parameter values, not applying DATEADD() operations data in the loanFirstPmtDate column.