如何返回MySQL链式调用存储过程?

时间:2016-10-07 02:29:20

标签: mysql stored-procedures

我有4个SP。 get_revenueget_hotel_revenueget_region_revenueget_division_revenue

因此get_revenue将首先选择正确的数据输入其他3 SP。 以下是我正在尝试的事情:

SELECT @hotel_id := hotel.hotel_id, @region_id := region_id, @division_id := division_id FROM campaign
LEFT JOIN hotel ON campaign.hotel_id = hotel.id
WHERE campaign.id = campaign_id;

#This is the part that doesnt return anything.
CALL get_hotel_revenue(@hotel_id);
CALL get_region_revenue(@region_id);
CALL get_division_revenue(@division_id);

但结果只返回3个变量。 如何从3个嵌套SP获得3个结果?

这是get_division_revenue的SP,与其他2相似。

DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_division_revenue`(IN division_id INT(11))
BEGIN
  SELECT sum(revenue) FROM data
  WHERE data.property_id IN 
  (
    SELECT hotel_id FROM hotel
    WHERE hotel.division_id = division_id
  );
END;;
DELIMITER ;

1 个答案:

答案 0 :(得分:0)

添加第二个参数OUT变量:

DELIMITER ;;
CREATE PROCEDURE `get_division_revenue`(IN division_id INT(11), OUT out_result int)
BEGIN
  -- and store the query result in that variable 
  SET out_result = (
      SELECT sum(revenue) FROM data
      WHERE data.property_id IN 
      (
        SELECT hotel_id FROM hotel
        WHERE hotel.division_id = division_id
      )
    );

END;;
DELIMITER ;

之后,更改添加会话变量的第一个存储过程:

-- Create the session variables before call procedures
set @hotel_revenue = null;
set @region_revenue = null;
set @division_revenue = null;

-- Now you can acll the procedures with those variables
CALL get_hotel_revenue(@hotel_id,@hotel_revenue);
CALL get_region_revenue(@region_id,@region_revenue);
CALL get_division_revenue(@division_id,@division_revenue);

现在@hotel_revenue@region_revenue@division_revenue可以根据需要获得每个存储过程的结果。

在程序结束时添加一个带有变量的选择:

SELECT @hotel_revenue as hotel_revenue, 
    @region_revenue as region_revenue,
    @division_revenue as division_revenue;