MySQL存储过程案例语句语法错误

时间:2018-09-08 07:47:30

标签: mysql syntax-error case

我正在尝试创建一个存储过程,该过程通过将订购数量和产品费率乘以不同的表格(称为费率)并从预订表中获取数量来计算金额。计算后,我希望将其插入到另一个表格中表“金额”。我总共有5个产品。例如,如果product ='abc',则将'abc'的金额放入,并为其余产品的金额插入零。在这里,我正在使用一个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 ;

1 个答案:

答案 0 :(得分:0)

在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

如果您要保持数据库技能的可移植性,那么基本上,您要放入案例“结果”中的唯一一件事就是值,而不是陈述

IF ELSEIF ELSE用于主要数据库中的条件程序流,有关它的MySQL文档在这里:

https://dev.mysql.com/doc/refman/8.0/en/if.html

此外,对于字符串,更喜欢使用'而不是'-双引号是MySQL与标准的另一种偏离