使用mysql进行递归调用的存储过程

时间:2015-11-17 06:02:24

标签: mysql stored-procedures recursion

enter image description here enter image description here get legside from binary

我尝试过使用带有递归调用的存储过程。我需要根据leg1基于leg1显示相关名称

但它显示错误,例如#1414 - OUT或INOUT参数2用于例行sample.getVolume不是BEFORE触发器中的变量或NEW伪变量

这是我的代码,

DELIMITER $$
CREATE PROCEDURE getVolume( IN param_name VARCHAR(255), OUT result VARCHAR(255 ))
BEGIN 
SELECT val INTO result FROM employee WHERE emp_name = param_name ;
IF result IS NULL THEN
select result;
ELSE     
CALL getVolume(result, '');
END IF;
END $$
DELIMITER ;



SET @@GLOBAL.max_sp_recursion_depth = 255;
SET @@session.max_sp_recursion_depth = 255; 
call getVolume('new', @result);
select @result;

2 个答案:

答案 0 :(得分:3)

@Shadow的答案是正确的。这是一个可以帮助您的实用示例:

DELIMITER //

DROP TABLE IF EXISTS `employee`//
DROP PROCEDURE IF EXISTS `getVolume`//

CREATE TABLE `employee` (
  `emp_name` VARCHAR(255),
  `val` VARCHAR(255)
)//

INSERT INTO `employee` (`emp_name`, `val`)
VALUES
('demo', 'new'),
('new', 'd.new'),
('d.new', 'view'),
('view', 'hello'),
('hello', NULL)
//

CREATE PROCEDURE `getVolume`(
  IN `param_name` VARCHAR(255),
  OUT `result` VARCHAR(255)
)
BEGIN
  DECLARE `next_param_name` VARCHAR(255);
  SELECT `val` INTO `next_param_name`
  FROM `employee`
  WHERE `emp_name` = `param_name`;

  IF `next_param_name` IS NULL THEN
    SET `result` := `param_name`;
  ELSE
    -- CALL `getVolume`(`result`, '');
    CALL `getVolume`(`next_param_name`, `result`);
    -- SET `result` := CONCAT(`param_name`, ',', IFNULL(`result`, ''));
  END IF;
END//

DELIMITER ;

SQL Fiddle demo

答案 1 :(得分:1)

问题是当你在getresult中调用getResult()时,你将一个空字符串常量作为参数传递:

CALL getVolume(result, '');

改为声明变量并将其作为参数传递。在getVolume调用之后,不要忘记将getVolume返回的内容与带分隔符的结果变量连接起来。你确定255个字符足以容纳所有值吗?