在mysql中创建存储过程

时间:2017-03-30 11:44:24

标签: mysql stored-procedures

此代码有什么问题

CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);

    select concat('#GNC', '3') into main_id;  #error shows here


    declare m1 int;
    declare m2 int;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;



    select m1, m2, main_id;
END

它给出了错误的结果。如果我删除if语句就可以了。

2 个答案:

答案 0 :(得分:0)

你几乎就在那里:)我看到的唯一问题是你所有的声明都不在你的逻辑的开头你没有使用分隔符如@阿尔瓦罗;试试这个:

DELIMITER $$

CREATE PROCEDURE `diff`()
  BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);
    declare m1 INT;
    declare m2 int;

    select concat('#GNC', '3') into main_id; 

     select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
      TRUNCATE `grocery`.`order_seqid`;
    end if;



    select m1, m2, main_id;
  END $$

答案 1 :(得分:0)

您缺少分隔符,并且声明部分不包含任何简单的SELECT语句。 在您的代码中只需替换

   declare main_id varchar(20);
    select concat('#GNC', '3') into main_id;  #error shows here
    declare m1 int;
    declare m2 int;

declare main_id varchar(20);
declare m1 int;
declare m2 int;
select concat('#GNC', '3') into main_id;  #error shows here

尝试以下代码

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);
    declare m1 int;
    declare m2 int;
    select concat('#GNC', '3') into main_id  ;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END

希望这会有所帮助。