Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a stored procedure for each row returned by a query in MySQL

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?

like image 634
Mr. Boy Avatar asked Jan 14 '13 21:01

Mr. Boy


People also ask

Can we call stored procedure in select statement in MySQL?

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.

Can I call a stored procedure from a view in MySQL?

No, you cannot.

Can we call stored procedure in select statement?

We can not directly use stored procedures in a SELECT statement.

How do you call a stored procedure with parameters in MySQL?

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.


1 Answers

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 
like image 135
eggyal Avatar answered Oct 09 '22 14:10

eggyal