我正在尝试创建一个存储过程,该过程通过将订购数量与来自不同表(称为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 ;
1条答案
按热度按时间hvvq6cgz1#
在sql中(一般情况下),case不用于程序条件流,而是用于在变量赋值中返回奇异值。mysql确实允许这样做,但我建议避免使用它,因为其他数据库系统不支持它
典型场景:
避免这种情况:
如果您是在保持数据库技能的交叉可移植性,那么在案例的“结果”中,您应该放的基本上是一个值,而不是一个语句
如果elseif else用于主要数据库中的条件程序流,则其mysql文档如下:
https://dev.mysql.com/doc/refman/8.0/en/if.html
另一方面,我们更喜欢使用“for string,not”-双引号是mysql与标准的另一个不同之处