answer should be correct for all possible scenarios. below i have write some of possible scenario.
Eg -
Number of month between 2012-12-31 and 2013-02-28 Answer should be - 2
Number of month between 2019-01-31 and 2019-03-01 Answer should be - 1
answer should be correct for all possible scenarios. below i have write some of possible scenario.
Eg -
Number of month between 2012-12-31 and 2013-02-28 Answer should be - 2
Number of month between 2019-01-31 and 2019-03-01 Answer should be - 1
A simple and easy way, just copy and paste this example SQL to MSSQL and execute. If you want, you can create a function using this code and execute.
DECLARE @StartDate DATE = '2019-01-31'
DECLARE @EndDate DATE = '2019-02-28'
SELECT
DATEDIFF(MONTH, @StartDate, @EndDate)+
(CASE
WHEN FORMAT(@StartDate,'yyyy-MM') != FORMAT(@EndDate,'yyyy-MM') AND
DATEPART(DAY,@StartDate) > DATEPART(DAY,@EndDate) AND
DATEPART(DAY,@EndDate) = DATEPART(DAY,EOMONTH(@EndDate)) THEN 0
WHEN FORMAT(@StartDate,'yyyy-MM') != FORMAT(@EndDate,'yyyy-MM') AND
DATEPART(DAY,@StartDate) > DATEPART(DAY,@EndDate) THEN -1
ELSE 0 END) AS NumberOfMonths