MySQL存储过程分隔符

时间:2017-07-25 08:28:44

标签: mysql stored-procedures

我尝试创建以下程序:

DROP PROCEDURE IF EXISTS my_super_procedure;
DELIMITER $$
CREATE PROCEDURE my_super_procedure(IN in_id VARCHAR(255), IN in_from_date timestamp, IN in_to_date timestamp)
BEGIN

    DROP TEMPORARY TABLE IF EXISTS tblResults;
    CREATE TEMPORARY TABLE IF NOT EXISTS tblResults(
        selected_date timestamp,
        total_value int
    ); -- !!!!!  Syntax error: missing END

    DECLARE tmp_date timestamp;
    SET tmp_date = in_from_date;

    WHILE tmp_date < in_to_date DO

        SELECT count(*) as total_events FROM event e where e.scheduled between tmp_date and tmp_date + interval 1 day;
        set tmp_date = DATE_ADD(tmp_date, INTERVAL 1 DAY);
    END WHILE;
END$$

DELIMITER ;

call my_super_procedure("3dccd75a-4c8e-11e7-bf68-5ce0c56861d1", "2017-06-24 04:16:43", "2017-06-28 04:16:43");

我是存储过程的新手。 我该如何解决这个错误?

1 个答案:

答案 0 :(得分:2)

在开头声明所有变量,而不是在代码的中间。

DROP PROCEDURE IF EXISTS my_super_procedure;
DELIMITER $$
CREATE PROCEDURE my_super_procedure(IN in_id VARCHAR(255), IN in_from_date timestamp, IN in_to_date timestamp)
BEGIN
    DECLARE tmp_date timestamp;

    DROP TEMPORARY TABLE IF EXISTS tblResults;
    CREATE TEMPORARY TABLE IF NOT EXISTS tblResults(
        selected_date timestamp,
        total_value int
    );

    SET tmp_date = in_from_date;

    WHILE tmp_date < in_to_date DO

        SELECT count(*) as total_events FROM event e where e.scheduled between tmp_date and tmp_date + interval 1 day;
        set tmp_date = DATE_ADD(tmp_date, INTERVAL 1 DAY);
    END WHILE;
END$$

DELIMITER ;