I've read many threads here about mysql loops that throw errors. So do mine but neither of the solutions I've tried seem to fix my problem.
I'm working with some stored procedures and I'm trying to get the following loop to work:
DECLARE counter INT(11) DEFAULT 0;
add_rows: LOOP
INSERT INTO vote_orders (id, vote_id, vote_order, vote_candidate)
WHILE counter <= @number_of_candidates DO
SELECT NULL, vote_id, counter, vote_candidate_a
FROM votes_copy
IF counter = @number_of_candidates THEN
LEAVE add_rows;
END IF;
UNION
END WHILE;
END LOOP add_rows;
This always throws the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE counter INT(11) DEFAULT 0;
add_rows: LOOP
INSERT INTO vote_orde' at line 30
I've tried to only store the declaration of 'counter' which seems to work perfect but as soon as I try to add the loop it fails. (@number_of_candidates
is a stored procedure that's called from the loop, the UNION
is supposed to union each selects until counter reaches @number_of_candidates
).
Do you have any suggestions on why this won't work?