简体   繁体   中英

Getting a MYSQL 1064 error when creating a function

DELIMITER $$

    CREATE FUNCTION nameOfFunct(intIn int)
    RETURN int
    BEGIN
        DECLARE intOut INT;
        SET intOut = SELECT count(*)
            FROM tableToTakeFrom
            WHERE columToCompareTo = intIn;

        RETURN intOut;
    END;
        $$

DELIMITER;

If I try to run this all I get is:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RETURN int
BEGIN
DECLARE intOut INT;
SET intOut = select count(' at line 2

A couple of changes to resolve the problem:

DELIMITER $$

CREATE FUNCTION nameOfFunct(intIn INT)
-- RETURN INT
RETURNS INT
BEGIN
    DECLARE intOut INT;
    /*SET intOut = SELECT COUNT(*)
        FROM tableToTakeFrom
        WHERE columToCompareTo = intIn;*/
    SET intOut = (SELECT COUNT(*)
        FROM tableToTakeFrom
        WHERE columToCompareTo = intIn);
    RETURN intOut;
END $$

DELIMITER ;

Defining the return type is done by the RETURNS keywrod, not the RETURN keyword:

CREATE FUNCTION nameOfFunct(intIn int)
RETURNS int
BEGIN
    DECLARE intOut INT;
    SET intOut = SELECT count(*) 
                 FROM   tableToTakeFrom
                 WHERE  columToCompareTo = intIn;
    RETURN intOut;
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM