Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(MySQL) Stored Procedure - Looping through result

We're migrating and application from PostgreSQL to MySQL.
Basically, I would like to loop through a result in MySQL.

SELECT col1 FROM table1; <--- (1) Get the result from this query.

LOOP THROUGH col1Result

SELECT myCol FROM table2 WHERE thisCol = col1Result <--- Equal to every single results from the previous query.

END LOOP;

I also found this reference
http://dev.mysql.com/doc/refman/5.0/en/cursors.html
However, I'm stuck with this line.

FETCH cur1 INTO a, b;

Doesn't that get every single result of cur1 into variables a and b? How would I make sure that I'm currently on the first index of variable a?

Here's an example on how the result will be used on my end (Written in PostgreSQL).

FOR my_record IN

   SELECT DISTINCT col1
   FROM            table1
   WHERE           col2 = param1;

LOOP

   SELECT DISTINCT col4
   FROM            table2
   WHERE           col3 = my_record.col1;

   IF true THEN
      RAISE EXCEPTION '%', 'ERROR MESSAGE' || my_record.col1;
   END IF

   SELECT DISTINCT col5
   FROM            table3
   WHERE           col6 = my_record.col1;

   IF true THEN
      RAISE EXCEPTION '%', ERROR MESSAGE' || my_record.col1;
   END IF;

END LOOP;
like image 603
Michael 'Maik' Ardan Avatar asked Oct 03 '22 08:10

Michael 'Maik' Ardan


2 Answers

cur1 would read the results of the each row. Each time it loops it gets the next row. So the first time it loops it will get the first row. This will go on until the loop breaks or no more rows are available (in which case a No Data condition occurs.

See this for more. Hope it helps.

like image 173
woofmeow Avatar answered Oct 07 '22 19:10

woofmeow


Why would you use a loop when you can do the processing with a join?

select mycol
from table2 t2 join
     table1 t1
     on t1.col1 = t2.thiscol;

This works in both Postgres and MySQL.

like image 25
Gordon Linoff Avatar answered Oct 07 '22 18:10

Gordon Linoff