skip to Main Content

I’m a student and I’m trying to get my function to return the result of my select, but I don’t know what to put in the RETURN.

I have tried to create functions with mathematical operations for example, and it works correctly for example:

DELIMITER $$
CREATE FUNCTION `getScore`(`a` INT, `b` INT, `c` INT) RETURNS INT
BEGIN
    RETURN a + b + c;
END$$
DELIMITER ;

SELECT getScore(0.3, 0.4, 0.5);

But my problem is in this function, I don’t know what to put in the RETURN or how to scrutinize the function:

DELIMITER $$

CREATE FUNCTION `getCharacters`() RETURN 
BEGIN

        SELECT * 
        FROM `characters` 
        WHERE `level` > 50

END$$

DELIMITER ;

SELECT getCharacters();

I have the next error:

A "RETURNS" keyword was expected. (near "RETURN" at position 34)

Thank you for any help and excuse me for my English.

2

Answers


  1. MySQL stored functions only return a single scalar value. They cannot return result sets. Functions can be used in a scalar expression context.

    You can use a stored procedure to return a result set, but you can’t use it in an expression. You can only run a procedure with CALL.

    Login or Signup to reply.
  2. A MySQL function can only return a single value. You can use a stored procedure, instead:

    DELIMITER $$
    
    CREATE PROCEDURE `getCharacters`() 
    BEGIN
    
            SELECT * 
            FROM `characters` 
            WHERE `level` > 50;
    
    END $$
    
    DELIMITER ;
    
    CALL getCharacters;
    

    More info about the difference between stored procedures and functions can be found here: MySQL stored procedure vs function, which would I use when?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search