Question

Given the 2 months and years. NO day mentioned. I need to calculate the difference between those two dates in SQL.Example of the columns in SQL server DB.

MonthFROM    YearFROM   MonthTo  YearTO

12           2010       1        2012

Output should be 14 months.

Was it helpful?

Solution 3

SQL Fiddle of the following:

SELECT DATEDIFF(month, 
         CONVERT(VARCHAR(19),
                 CAST(MonthFROM as varchar) + '/01/' + CAST(YearFROM as varchar),
                 101), 
         CONVERT(VARCHAR(19), 
                 CAST(MonthTo as varchar) + '/01/' + CAST(YearTO as varchar), 
                 101)) + 1 AS MonthPast
FROM MyTable;

The result would be:

MONTHPAST
14

The actual months difference is 13 but you had 14 as what you are expecting as a result. If your calculation was wrong and you indeed need 13 then remove the + 1 from the query.

OTHER TIPS

It is not good idea to keep date in this manner.

SELECT DATEDIFF(mm, CAST(YearFROM as varchar) + RIGHT('0' + CAST(MonthFROM as varchar), 2) + '01',
                      CAST(YearTO as varchar) + RIGHT('0' + CAST(MonthTO as varchar), 2) + '01')

Please try the following using simple arithmetic:

Select (YearTo - YearFrom) * 12 + MonthTo - MonthFrom + 1 as Difference
  from MyTable;

If you are using SQL Server 2012 here is the quick way to do this

SELECT DATEDIFF(month, DATEFROMPARTS (YearFROM, MonthFROM, 01),
                DATEFROMPARTS (YearTO, MonthTo, 01))
FROM YourTable

Demo on SQL Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top