简体   繁体   中英

Using a Case Statement on CHARs in a MySQL Stored Function

I am trying to write a stored function that takes the value in a CHAR(3) (an acronym), applies a CASE to it, and converts it to another string. My table schema looks like:

CREATE TABLE roster (
    id VARCHAR(9) PRIMARY KEY,
    class_level CHAR(2)
);

and an attempt at writing the stored function:

DELIMITER $$
CREATE FUNCTION classlevel (level CHAR(2))
    RETURNS TINYTEXT DETERMINISTIC
    BEGIN
    DECLARE `result` TINYTEXT;
    SET `result` = "";
    SET `result` =
        CASE
            WHEN "SR" THEN "Senior"
            WHEN "JR" THEN "Junior"
            WHEN "SO" THEN "Sophomore"
            WHEN "FR" THEN "Freshman"
            ELSE "Unknown"
        END;
    RETURN `result`;
    END$$

When I try to execute the function on my table, I get an error:

mysql> select classlevel(class_level) from extended_roster;
ERROR 1292 (22007): Truncated incorrect DOUBLE value: 'SR'

I don't have any DOUBLE s in my schema, so I don't know why these strings are being interpreted as DOUBLE .

First, your case expression might be as follow

CASE (level)
     WHEN "SR" THEN "Senior"
     WHEN "JR" THEN "Junior"
     WHEN "SO" THEN "Sophomore"
     WHEN "FR" THEN "Freshman"
     ELSE "Unknown"
END;

Since, you don't have defined any expression or column for case

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