Reputation: 3638
Am trying to fetch out a field through stored procedure and I used following query. I aimed at fetching out multiple rows, but it executes the result successfully only when a single row exists. Or else it returns an error as I mentioned below.
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 personnel 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 personnel
lft
- use to check the condition, it is also one of the field of table personnel
personnel
- table name
Upvotes: 9
Views: 66047
Reputation: 176
You can use a cursor in MySQL.
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;;
Upvotes: 7
Reputation: 209
Just had the same question. After a little research I found a solution in the official MySQL documentation:
It requires MySQL 5.5.3 or higher.
In contrast to the inital stored procedure from @Bala.C it doesn't use an out
parameter.
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;
Upvotes: 10
Reputation: 121932
The error is not in your procedure. The error is in your query - it returns more then one row, but you cannot set multiple result into scalar value 'emp1'.
You should limit your query so that it returns one row.
How to retreive multiple rows from stored procedure in mysql?
Upvotes: 11