1

I'm trying to create a function in MySQL, but getting a syntax error. This is my function:

DELIMITER $$
CREATE FUNCTION gg () 
RETURNS char(8)
DETERMINISTIC
BEGIN 
  DECLARE cod varchar(8);
  select RIGHT(MAX(idCurso),7) into cod from Curso;
  IF cod is null then
        set cod = 'C' + right('0000000' + convert(varchar(7),1),7);
    else
        set cod = 'C' + right('0000000' + convert(varchar(7), @id +1),7)
    return cod;
END$$
DELIMITER ;

I am getting this error in the set cod after the if cod is null then:

"cod" is not valid at this position, expecting an identifier

What am I doing wrong?

5
  • share the error Commented Sep 10, 2019 at 16:09
  • @Mario, can you explain what you want to achieve with this line set cod = 'C' + right('0000000' + convert(varchar(7),1),7); Commented Sep 10, 2019 at 16:16
  • 1
    Last I checked, MySQL does not use + for concatenation; but it's been a while since I checked. Also, it looks like the arguments for CONVERT might be backwards...and you have no END IF Make sure you are using documentation for MySQL, not MSSQL, nor Oracle, nor sqlite, etc.. Commented Sep 10, 2019 at 16:19
  • + is an arithmetic operator in mysql use concat instead.You aren't terminating your second set statement and your first set statement doesn't make sense. Commented Sep 10, 2019 at 16:21
  • @JitendraYadav I'm trying to create an id with this structure: 'C000000X' being 'x' a consecutive number. Commented Sep 10, 2019 at 16:22

1 Answer 1

3

There are many issues with your function.

  • + icon doesn't perform concatenation in MySQL, it is used for sum. Use CONCAT or CONCAT_WS for the same.
  • Improper use of CONVERT. Please see documentation CONVERT
  • Use LPAD to pad 0 to the left of your integer value and make it length to 7.
  • Removed @a, don't know from where you're accessing it, replaced it with cod value and adding 1 to it.
  • Missed END IF clause.
DELIMITER $$
CREATE FUNCTION gg () RETURNS CHAR(8) DETERMINISTIC 
BEGIN 
    DECLARE cod VARCHAR(8);
    SELECT
        RIGHT(MAX(idCurso),7) INTO cod
    FROM Curso; 

    IF cod IS NULL THEN 
        SET cod = CONCAT('C', LPAD(1, 7, '0')); 
    ELSE 
        SET cod = CONCAT('C', LPAD(cod + 1, 7, '0')); 
    END IF; 
    RETURN cod; 
END$$
DELIMITER ;
Sign up to request clarification or add additional context in comments.

1 Comment

@MarioVasquez, happy to help. For any MySQL statement, check whether it is right and how to use it. This is the best way to learn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.