I am creating a stored function in MYSQL Workbench that takes a date and returns the quarter of that fiscal year. I came up with the following code script. The SQL Editor checked the statements and accepted this function has no syntax errors.
CREATE FUNCTION `get_fiscal_quarter`(calendar_date DATE) RETURNS char(2)
DETERMINISTIC
BEGIN
DECLARE quart CHAR(2);
DECLARE quar CHAR(2);
SELECT CASE
WHEN MONTH(calendar_date) IN (9,10,11) THEN quart = 'Q1'
WHEN MONTH(calendar_date) IN (12,1,2) THEN quart = 'Q2'
WHEN MONTH(calendar_date) IN (3,4,5) THEN quart = 'Q3'
WHEN MONTH(calendar_date) IN (6,7,8) THEN quart = 'Q4'
END
INTO quar;
RETURN quar;
END
But when I tried to applying the get_fiscal_quarter
function on a date
value, it is returning NULL
. Where am I doing wrong?
I tried using the IF Statement but ran into many errors related to delimiters.
Statement is incomplete, expecting IF
Statement is incomplete, expecting END
delimiter is not valid at this position, expecting CREATE
I understood that MySQL Workbench script editor is automatically applying the delimiters code when I clicked the apply and so not accepting manually giving the DELIMITER $$
. But due to this, I'm getting this infinite loop of statement is incomplete
syntax errors when I tried to use ;
delimiter and END
the CASE/IF
. I declared 2 variables to use in CASE statement to escape these errors. But didn't get the expected result.
What is the correct way to write CASE and IF statements to create the stored functions in the MySQL WorkBench? It's so confusing to figure out the bug?
CodePudding user response:
CREATE FUNCTION `get_fiscal_quarter`(calendar_date DATE)
RETURNS char(2)
DETERMINISTIC
RETURN CASE WHEN MONTH(calendar_date) IN (9,10,11) THEN 'Q1'
WHEN MONTH(calendar_date) IN (12,1,2) THEN 'Q2'
WHEN MONTH(calendar_date) IN (3,4,5) THEN 'Q3'
WHEN MONTH(calendar_date) IN (6,7,8) THEN 'Q4'
END;