I am trying to use a cursor in MySQL to call a stored procedure many times. I want to call it as many times as a value for my_id
exists in some temporary table, and iterate through those ids and concatenate the results.
Anyway, I'm having trouble with this part of the process:
DECLARE curs CURSOR FOR
SELECT something FROM somewhere;
I don't want to select something from somewhere. I want something like
DECLARE curs CURSOR FOR
CALL storedproc(@an_id);
Can the DECLARE
statement be used to call a stored proc? Or does it have to be associated with a SELECT
only? Googling around, I'm afraid that the latter is the case.
Not possible and documentation is pretty clear on that
Using a cursor requires some standard boilerplate code to surround it.
Using a cursor to call a stored procedure for each set of values from the table requires essentially the same boilerplate. You
SELECT
the values you want to pass, from wherever you're getting them (which could be a temporary table, base table, or view, and can include calls to stored functions) and then call the procedure with those values.I've written an syntactically valid example of that boilerplate code, below, with comments to explain what each component is doing. There are few things I dislike more than being asked to just do something "just because" -- so everything is (hopefully) explained.
You mentioned calling the procedure with multiple values, so this example uses 2.
Note that there events that happen her are in a specific order for a reason. Variables have to be declared first, cursors have to be declared before their continue handlers, and loops have to follow all of those things. This gives an impression that there's some fairly extreme inflexibility, here, but that's not really the case. You can reset the ordering by nesting additional code inside
BEGIN
...END
blocks within the procedure body; for example, if you needed a second cursor inside the loop, you'd just declare it inside the loop, inside anotherBEGIN
...END
.