MySQL存储过程无法添加值

时间:2019-01-21 18:14:38

标签: mysql stored-procedures

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(p_barcode int)

BEGIN

DECLARE q1 int;

DECLARE q2 int;

DECLARE q3 int;

DECLARE total int;

SET total :=0;

SELECT sum(adjustment_quantity) INTO q1 FROM adjustment_inventory WHERE item_barcode = p_barcode group by adjustment_quantity;

SELECT sum(opening_stock) INTO q2 FROM openingstock
WHERE item_barcode = p_barcode group by opening_stock;

SELECT sum(inwardquantity) INTO q3
 FROM inwardmaster WHERE item_barcode = p_barcode group by inwardquantity;

    IF q1 IS NULL THEN

    SET q1 := 0;

    END IF;

    IF q2 IS NULL THEN

    SET q2 := 0;

    END IF;

    IF q3 IS NULL THEN

 SET q3 := 0;

    END IF;

    SELECT q1;
    SELECT q2;
    SELECT q3;
    SELECT q1+q2+q3;
    END$$

每次都会返回错误答案。例如q1 = 100 q2 = 200 q3 = 100其返回值100

1 个答案:

答案 0 :(得分:1)

您不需要为此使用存储过程

set @barcode = '1234';

select 
    coalesce((
      SELECT sum(coalesce(adjustment_quantity,0)) 
      FROM adjustment_inventory 
      WHERE item_barcode = @p_barcode
    ),0) + 
    coalesce((
      SELECT sum(opening_stock) 
      FROM openingstock
      WHERE item_barcode = @p_barcode
    ), 0) + 
    coalesce((
      SELECT 
      sum(coalesce(inwardquantity,0))
      FROM inwardmaster WHERE item_barcode = @p_barcode
    ), 0) res
From Dual
;

如果您确实要使用该过程,请检查下面的代码

DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(p_barcode int)
BEGIN
  DECLARE q1 int;
  DECLARE q2 int;
  DECLARE q3 int;
  DECLARE total int;
SET total :=0;
  SELECT coalesce(sum(adjustment_quantity), 0) INTO q1 FROM adjustment_inventory WHERE item_barcode = p_barcode;
  SELECT coalesce(sum(opening_stock), 0) INTO q2 FROM openingstockWHERE item_barcode = p_barcode;
  SELECT coalesce(sum(inwardquantity), 0) INTO q3 FROM inwardmaster WHERE item_barcode = p_barcode;

  SELECT q1;
  SELECT q2;
  SELECT q3;

  set total = q1+q2+q3;

  SELECT total;
END$$