MySQL用例语句进入存储过程

时间:2014-07-20 06:30:08

标签: mysql sql stored-procedures

我想在CASE的存储过程中使用IS NOT NULL语句,但是当我想保存它时出错:

ERROR:

  

MySQL说:1064 - 你的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便在正确的语法附近使用   'ELSE SET @v_delay:= 0 END在第19行插入`ts'

我的存储过程:

BEGIN

    DECLARE v_user_start_time INT UNSIGNED;
    DECLARE v_delay           INT(11);
    DECLARE v_pyear           INT UNSIGNED;
    DECLARE v_mounth          INT UNSIGNED;

    SET @v_pyear     = pyear    ( _datetime_in ) ;
    SET @v_mounth  = pmonth( _datetime_in );

    SET @v_user_start_time := (SELECT `start_time` FROM `tsms_range_time` WHERE `user_id` = _user_id);

    /* Check for first record today for calculate Delay*/
    SET @v_is_new := (SELECT id from `tsms_entry_exit` WHERE `datetime_in` = NOW() );
    /* calculate USER delay */
    CASE WHEN @v_is_new  IS NOT NULL 
            THEN 
                    SET @v_delay := SEC_TO_TIME (TIME_TO_SEC(_datetime_in) - TIME_TO_SEC(@v_user_start_time)) ;
            ELSE
                    SET @v_delay:=0;
    END CASE;

INSERT INTO `tsms_entry_exit` 
        (
            `user_id`,
            `datetime_in`,
            `datetime_out`,
            `delay`,
            `period`
        )
    VALUES
        (
           _user_id,
           _datetime_in,
           _datetime_out,
           @v_delay,
           CONCAT(@v_pyear, @v_mounth)
        );
        SELECT ROW_COUNT() AS 'Affected rows';
END

2 个答案:

答案 0 :(得分:0)

我相信您最好使用IF .. ELSE构造,如下所示

IF(@v_is_new  IS NOT NULL) 
THEN 
SET @v_delay := SEC_TO_TIME (TIME_TO_SEC(_datetime_in) - TIME_TO_SEC(@v_user_start_time)) ;
ELSE
SET @v_delay:=0;
END IF; 

您可以执行类似

的操作
SELECT @v_delay := CASE WHEN @v_is_new  IS NOT NULL THEN 
SEC_TO_TIME (TIME_TO_SEC(_datetime_in) - TIME_TO_SEC(@v_user_start_time)) 
ELSE 0 END; 

答案 1 :(得分:0)

case语句不是存储过程代码的控制流逻辑。它是查询中使用的逻辑。 if语句是控制流逻辑。你可以做你想做的事情:

SET @v_delay = (CASE WHEN @v_is_new
                     THEN SEC_TO_TIME(TIME_TO_SEC(_datetime_in) - TIME_TO_SEC(@v_user_start_time))
                     ELSE 0
                 END)

还要注意其他一些错误:

  • SET仅使用=而非:=
  • 您不希望在功能名称后面留空格。