I want a MySQL stored procedure which effectively does:
foreach id in (SELECT id FROM objects WHERE ... ) CALL testProc(id)
I think I simply want the MySQL answer to this question but I don't understand cursors well: How do I execute a stored procedure once for each row returned by query?
In MySQL, it is not possible to use select from procedure in FROM clause. You can use CALL command and after that the SELECT statement can be executed. Here is the query to display records from the table using select statement after calling stored procedure.
No, you cannot.
We can not directly use stored procedures in a SELECT statement.
Example: Calling a stored procedure with parametersmysql> CREATE TABLE Emp (Name VARCHAR(255), Salary INT, Location VARCHAR(255)); Assume we have created a stored procedure InsertData which accepts the name, salary and location values and inserts them as a record into the above create (Emp) table.
Concepts such as “loops” (for-each, while, etc) and “branching” (if-else, call, etc) are procedural and do not exist in declarative languages like SQL. Usually one can express one’s desired result in a declarative way, which would be the correct way to solve this problem.
For example, if the testProc
procedure that is to be called uses the given id
as a lookup key into another table, then you could (and should) instead simply JOIN
your tables together—for example:
SELECT ... FROM objects JOIN other USING (id) WHERE ...
Only in the extremely rare situations where your problem cannot be expressed declaratively should you then resort to solving it procedurally instead. Stored procedures are the only way to execute procedural code in MySQL. So you either need to modify your existing sproc so that it performs its current logic within a loop, or else create a new sproc that calls your existing one from within a loop:
CREATE PROCEDURE foo() BEGIN DECLARE done BOOLEAN DEFAULT FALSE; DECLARE _id BIGINT UNSIGNED; DECLARE cur CURSOR FOR SELECT id FROM objects WHERE ...; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE; OPEN cur; testLoop: LOOP FETCH cur INTO _id; IF done THEN LEAVE testLoop; END IF; CALL testProc(_id); END LOOP testLoop; CLOSE cur; END
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