MySQL 在存储过程中的情况:错误代码:1064

Posted

技术标签:

【中文标题】MySQL 在存储过程中的情况:错误代码:1064【英文标题】:MySQL case when in stored procedure: Error Code: 1064 【发布时间】:2020-11-24 09:58:55 【问题描述】:

表:订单(字段:客户编号、状态) 要求:接受客户编号并返回已发货、取消、已解决和有争议的订单总数。 更多信息:https://www.mysqltutorial.org/mysql-stored-procedures-return-multiple-values/

## I am trying to implement this requirement using case when. the code is below: 
## using MySQLWorkBench
delimiter //
create procedure get_order_number_by_status(
    in cnumber int
    , out shipped int
    , out cancelled int 
    , out resolved int 
    , out disputed int 
    )
begin
    select case o.status  ## Error: "select is not valid at this position for...
        when 'Shipped' then  shipped :=shipped +1
        when 'Cancelled' then  cancelled :=cancelled +1
        when 'Resolved' then  resolved :=resolved +1
        when 'Disputed' then  disputed :=disputed +1
        else null
        end
    from customers c join orders o
    on c.customernumber = o.customernumber
    where c.customernumber = cnumber;
end //

我无法解决这个问题,需要帮助..

【问题讨论】:

这似乎比存储过程更适合VIEW。这实际上只是一些简单的GROUP BY 东西。 您应该在问题中包含 准确 和完整的错误文本。 MySQL 通常会在消息的其他部分准确指出问题发生的位置。 【参考方案1】:

不能以这种方式使用局部变量。只有用户定义的变量才允许内联赋值。

create procedure get_order_number_by_status(
    in cnumber int
    , out shipped int
    , out cancelled int 
    , out resolved int 
    , out disputed int 
    )
begin
    select case o.status 
        when 'Shipped' then  @shipped := @shipped +1
        when 'Cancelled' then  @cancelled := @cancelled +1
        when 'Resolved' then  @resolved := @resolved +1
        when 'Disputed' then  @disputed := @disputed +1
        else null
        end
    from customers c join orders o
    on c.customernumber = o.customernumber
    CROSS JOIN (SELECT @shipped:=0, @cancelled:=0, @resolved:=0, @disputed:=0) init
    where c.customernumber = cnumber;
    SET shipped := @shipped;
    SET cancelled := @cancelled;
    SET resolved := @resolved;
    SET disputed := @disputed;
end

fiddle

附言。为什么不简单

create procedure get_order_number_by_status(
    in cnumber int
    , out shipped int
    , out cancelled int 
    , out resolved int 
    , out disputed int 
    )

    select SUM(o.status = 'Shipped'),
           SUM(o.status = 'Cancelled'),
           SUM(o.status = 'Resolved'),
           SUM(o.status = 'Disputed')
    INTO shipped, cancelled, resolved, disputed
    from customers c join orders o
    on c.customernumber = o.customernumber
    where c.customernumber = cnumber
    GROUP BY o.status;

?

【讨论】:

以上是关于MySQL 在存储过程中的情况:错误代码:1064的主要内容,如果未能解决你的问题,请参考以下文章

mysql error (#1064) 存储过程创建错误

Mysql创建存储过程时出现ERROR 1064错误

MySQl 错误 #1064 存储过程 IF ELSE 带有多个 SELECT 语句

带有游标的 MySQL 存储过程

#1064 - MySQL 服务器版本在“END”错误附近使用正确的语法?

过程中的错误 1064