Not Amused
Not Amused

Reputation: 962

Processing Rows returned by a select statement within a stored procedure

Is there anybody out there who can tell me how I can fetch rows but within a stored procedure?

Let's say for example that I do

BEGIN 
   SELECT id, name, lastname, 
   FROM eyploees;

   --How can i process all the results within this procedure?

END<br/>

Upvotes: 2

Views: 2453

Answers (1)

iouri
iouri

Reputation: 2929

You need to use cursors:

DECLARE id_var INT;
DECLARE name_var VARCHAR(255);
DECLARE lastname_var VARCHAR(255);

DECLARE my_cursor CURSOR FOR SELECT id, name, lastname FROM employees;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN my_cursor;

read_loop: LOOP

    FETCH my_cursor INTO id_var, name_var, lastname_var;
    IF done THEN
      LEAVE read_loop;
    END IF;

    --Do some row work here using _var variables from above

END LOOP;

CLOSE my_cursor;

Upvotes: 4

Related Questions