Dynamic Query Execution and Output Assignment in MySQL Stored Procedure
In MySQL, it is possible to dynamically generate and execute queries within a stored procedure. However, to assign the result of a dynamic query to an OUT parameter, a slightly different approach is needed.
Consider the stored procedure code provided in the question:
CREATE PROCEDURE 'searchInvoice' ( OUT numOfRecords INT ) BEGIN DECLARE query1 TEXT; DECLARE query2 TEXT; SET query1 = 'SELECT COUNT(*) bla bla bla.....'; // Query1 to select the count of matching tuples.. SET query2 = 'SELECT * from bla bla bla....'; // Query2 to select original records... // later part of this both queries generate dynamically according to some IN parameters.. // now I wanna assign the output of the query1 into numOfRecords // and I wanna execute the query2 as well.. like this SET @Sql = query2; PREPARE STMT FROM @Sql; EXECUTE STMT; DEALLOCATE PREPARE STMT; // output of the query2 can be read in PHP END
To assign the output of query1 to the numOfRecords OUT parameter, the following steps can be taken:
SET @numOfRecords = 0;
DECLARE query1Cursor CURSOR FOR query1; OPEN query1Cursor; FETCH query1Cursor INTO @numOfRecords; CLOSE query1Cursor;
SET numOfRecords = @numOfRecords;
With this modified approach, the stored procedure can both execute dynamic queries and assign the output of specific queries to OUT parameters.
The above is the detailed content of How to Assign the Result of a Dynamic Query to an OUT Parameter in a MySQL Stored Procedure?. For more information, please follow other related articles on the PHP Chinese website!