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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With