Home > Enterprise >  Calculate years based on months in SQL Server
Calculate years based on months in SQL Server

Time:04-27

I want to write a function that takes the number of months as a parameter and does the following:

IF @months = 3 THEN '3 Months'
IF @months = 6 THEN '6 Months'
IF @months = 12 THEN '1 Year'
IF @months = 18 THEN '1.5 Year'
IF @months = 24 THEN '2 Year'

.... and so on

I can hardcode all of this using case statements but I wanted to know if there is a dynamic way of doing it. Thanks!

CodePudding user response:

Try this:

DECLARE @month INT=18
SELECT CASE WHEN t.divided >1 THEN CONCAT(t.divided,' Year') ELSE  CONCAT(CAST(t.divided AS INT),' Month') END 
FROM (
SELECT CAST(CASE WHEN @month<12 THEN @month ELSE @month/12.0 END AS DECIMAL(4,1)) divided
) t
  • Related