我试图通过存储过程获取字段,并使用了以下查询。我的目标是获取多行,但只有当存在一行时才能成功执行结果。否则它会返回错误,如下所述。
delimiter ;;
drop procedure if exists Sample1;;
CREATE PROCEDURE Sample1(IN lft1 INT,IN rgt1 INT, OUT emp1 VARCHAR(20))
BEGIN
SELECT p.emp into emp1 FROM personnell p WHERE p.lft>lft1 and p.rgt < rgt1 LIMIT 10;
END;;
call Sample1(1,10,@emp);;
select @emp;
MySQL said: Documentation
#1172 - Result consisted of more than one row
注意
-----
Sample1--- procedure name;
emp -----selected field from table personnell
lft -----use to check the condition,it is also one of the field of table personnell
personnell------table name
答案 0 :(得分:11)
错误不在你的程序中。错误在您的查询中 - 它返回多行,但您不能将多个结果设置为标量值'emp1'。
您应该限制查询,以便返回一行。
如何从mysql中的存储过程中检索多行?
答案 1 :(得分:5)
刚才有同样的问题。经过一番研究后,我在官方文档中找到了解决方案。 http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-tutorials-stored-routines-statements.html 它需要MySQL 5.5.3或更高版本。
与@ Bala.C的初始存储过程相反,它不使用out参数。
CREATE PROCEDURE get_data ()
BEGIN
SELECT Code, Name, Population, Continent FROM Country
WHERE Continent = 'Oceania' AND Population < 10000;
SELECT Code, Name, Population, Continent FROM Country
WHERE Continent = 'Europe' AND Population < 10000;
SELECT Code, Name, Population, Continent FROM Country
WHERE Continent = 'North America' AND Population < 10000;
END;
答案 2 :(得分:3)
您可以在MySql中使用Cursor
CREATE PROCEDURE Sample1(IN lft1 INT,IN rgt1 INT, OUT emp1 VARCHAR(20))
BEGIN
DECLARE p_emp INT;
DECLARE cur_emp CURSOR FOR SELECT p.emp FROM personnell p WHERE p.lft>lft1 and p.rgt < rgt1 LIMIT 10;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET noMoreRow = 0;
OPEN cur_emp;
LOOPROWS: LOOP
IF noMoreRow = 0 THEN
CLOSE cur_emp;
LEAVE LOOPROWS;
END IF;
FETCH cur_emp INTO p_emp;
SELECT p_emp;
END LOOP;
END;;