简体   繁体   中英

mysql case/when statement within procedure

I keep getting a 1064 Syntax Error after the first ";" in the first when statement. I have tried to no avail tips from here and here . Help anyone?

DELIMITER //

CREATE PROCEDURE `test` ()
BEGIN
    SELECT *,
        case 
        when variable_1 between 0.75 and 4     then 4;
        when variable_1 between 0    and 0.74  then "<4";
        when variable_1 between 4.1  and 365  then ">4";
        end case as variable_2;
END //

Amended question following the answers:

The actual code:

DELIMITER //

CREATE PROCEDURE `infant_outcomes`.`new_procedure` ()
BEGIN
SELECT * FROM CDI

        INNER JOIN


    -- CDI subquery grouping and filtering 
    (SELECT CDI.subj_CDI as subj_CDI_grouping, Min(hearing_age_CDI) min_hearing_age_CDI,
    case 
    when CDI.hearing_age_CDI between 1.75 and 4.25 then 3
    when CDI.hearing_age_CDI between 4.75 and 7.25 then 6

    end as hearing_age_CDI_group
    FROM CDI
    group by CDI.subj_CDI, hearing_age_CDI_group
    ORDER BY CDI.subj_CDI, CDI.hearing_age_CDI ASC) CDI_filtered

        on
            CDI.subj_CDI = subj_CDI_grouping
            AND CDI.hearing_age_CDI = CDI_filtered.min_hearing_age_CDI

    where hearing_age_CDI_group is not null
    ORDER BY 
    CDI.subj_CDI, CDI_filtered.hearing_age_CDI_group
END //

I'm getting a syntax error at "End //" While a combination of the two following answers works, the actual code itself throws that error...

Because you break statement.

SELECT *,
    case 
    when variable_1 between 0.75 and 4     then "4"
    when variable_1 between 0    and 0.74  then "<4"
    when variable_1 between 4.1  and 365  then ">4"
    end as variable_2;

You have missed semicolon

ORDER BY 
CDI.subj_CDI, CDI_filtered.hearing_age_CDI_group;
                                                ^________ this.

Case expressions end in "end", not "end case".

Remove the trailing "case":

DELIMITER //

CREATE PROCEDURE `test` ()
BEGIN
    SELECT *,
        case 
        when variable_1 between 0.75 and 4     then 4;
        when variable_1 between 0    and 0.74  then "<4";
        when variable_1 between 4.1  and 365  then ">4";
        end as variable_2; -- "case" removed
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