mysql存储过程case语句语法错误

2lpgd968  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(504)

我正在尝试创建一个存储过程,该过程通过将订购数量与来自不同表(称为rate)的产品的比率相乘,并从bookings表中获取数量来计算数量。在计算之后,我希望将其插入另一个表“amount”。我一共有5种产品。例如,如果product='',则将amount放入'',并将剩余产品的amount插入零。这里,我使用一个case语句抛出语法错误。请帮忙。

DELIMITER $$
CREATE PROCEDURE `calculate_amount` (IN IN_book_id INT,IN IN_qty INT )
-- begin
BEGIN
-- declare
DECLARE prdct VARCHAR(10);
DECLARE cust_id INT(5);
-- select into
SELECT Product FROM Bookings WHERE Book_id=IN_book_id INTO prdct;
SELECT Cust_id FROM Bookings WHERE Book_id=IN_book_id INTO cust_id;
-- conditionals & action
CASE prdct
WHEN "20ltr"
THEN INSERT INTO Amount(Cust_id,Book_id,Can,300ml,500ml,1lit,2lit) VALUES(cust_id,IN_book_id,(SELECT Rate.Can*Bookings.Qty FROM Rate,Bookings WHERE Bookings.Book_id=IN_book_id),0,0,0,0);

WHEN "300ml"
THEN INSERT INTO Amount(Cust_id,Book_id,Can,300ml,500ml,1lit,2lit) VALUES(cust_id,IN_book_id,0,(SELECT Rate.300ml*Bookings.Qty FROM Rate,Bookings WHERE Bookings.Book_id=IN_book_id),0,0,0); 

WHEN "500ml"
THEN 
INSERT INTO Amount(Cust_id,Book_id,Can,300ml,500ml,1lit,2lit) VALUES(cust_id,IN_book_id,0,0,(SELECT Rate.500ml*Bookings.Qty FROM Rate,Bookings WHERE Bookings.Book_id=IN_book_id),0,0); 

WHEN "1ltr"
THEN 
INSERT INTO Amount(Cust_id,Book_id,Can,300ml,500ml,1lit,2lit) VALUES(cust_id,IN_book_id,0,0,0,(SELECT Rate.1lit*Bookings.Qty FROM Rate,Bookings WHERE Bookings.Book_id=IN_book_id),0); 

WHEN "2ltr"
THEN 
INSERT INTO Amount(Cust_id,Book_id,Can,300ml,500ml,1lit,2lit) VALUES(cust_id,IN_book_id,0,0,0,0,(SELECT Rate.2lit*Bookings.Qty FROM Rate,Bookings WHERE Bookings.Book_id=IN_book_id)); 

ELSE 
    BEGIN
    END;
END CASE;
-- end
END;$$

DELIMITER ;
hvvq6cgz

hvvq6cgz1#

在sql中(一般情况下),case不用于程序条件流,而是用于在变量赋值中返回奇异值。mysql确实允许这样做,但我建议避免使用它,因为其他数据库系统不支持它
典型场景:

--doing varied logic:
name = CASE 
    WHEN num = 1 THEN 'one' 
    WHEN othernum = 2 THEN 'two' 
END

--testing a single variable for being equal to values:
name = CASE num 
  WHEN 1 THEN 'one' 
  WHEN 2 THEN 'two' 
END

避免这种情况:

CASE 
  WHEN num = 1 THEN name = 'one' 
  WHEN num = 2 THEN name = 'two' 
END

如果您是在保持数据库技能的交叉可移植性,那么在案例的“结果”中,您应该放的基本上是一个值,而不是一个语句
如果elseif else用于主要数据库中的条件程序流,则其mysql文档如下:
https://dev.mysql.com/doc/refman/8.0/en/if.html
另一方面,我们更喜欢使用“for string,not”-双引号是mysql与标准的另一个不同之处

相关问题