0

I want to insert a number in function and get in return the name of the month according to the number I have tried CASE, IF, SET and so on. Still not working (syntax error near IF line 6)

    ALTER FUNCTION fn_Return_monthname (@monthPart INT)
    returns VarChar(50) 
    begin
      declare valjund VarChar(50);
      SET valjund = 'Unknow month'
      IF @monthPart = 1;
        SELECT valjund = 'January'
      ELSE IF @monthPart = 2
        SELECT valjund = 'February'
      ELSE IF @monthPart = 3
        SELECT valjund = 'March'
      ELSE IF @monthPart = 4
        SELECT valjund = 'April'
      ELSE IF @monthPart = 5
       SELECT valjund = 'May'
      ELSE IF @monthPart = 6
       SELECT valjund = 'June'
      ELSE IF @monthPart = 7
       SELECT valjund = 'July'
      ELSE IF @monthPart = 8
       SELECT valjund = 'August'
      ELSE IF @monthPart = 9
       SELECT valjund = 'September'
      ELSE IF @monthPart = 10
       SELECT valjund = 'October'
      ELSE IF @monthPart = 11
       SELECT valjund =  'November'
      ELSE IF @monthPart = 12
       SELECT valjund =  'December'
      return valjund;
    end;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Your code looks like SQL Server, so I am adding that tag. When you ask a question about SQL, you should add a tag for the database you are really using. – Gordon Linoff Jan 11 '21 at 15:07

2 Answers2

0

IF @monthPart = 1; remove please ;

Sergey
  • 4,719
  • 1
  • 6
  • 11
0

In SQL Server, I would suggest datename():

select datename(month, datefromparts(2000, @monthpart, 1))

This assumes that your language settings are set to English. You can use format() instead if you need to insist on English.

To prevent an invalid value, use a case expression:

select (case when @monthpart between 1 and 12
             then datename(month, datefromparts(2000, @monthpart, 1))
             else 'Unknown month'
        end)

You can easily incorporate this logic into a simple function. However, I don't think a UDF is really needed for this purpose.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786