MySQL 存储过程中的动态查询执行和输出分配
在 MySQL 中,可以在存储过程中动态生成和执行查询。但是,要将动态查询的结果分配给 OUT 参数,需要采用稍微不同的方法。
考虑问题中提供的存储过程代码:
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
要分配将 query1 的输出输出到 numOfRecords OUT 参数,可以采取以下步骤:
SET @numOfRecords = 0;
DECLARE query1Cursor CURSOR FOR query1; OPEN query1Cursor; FETCH query1Cursor INTO @numOfRecords; CLOSE query1Cursor;
SET numOfRecords = @numOfRecords;
通过这种修改后的方法,存储过程可以两者都执行动态查询并将特定查询的输出分配给 OUT 参数。
以上是如何将动态查询的结果分配给MySQL存储过程中的OUT参数?的详细内容。更多信息请关注PHP中文网其他相关文章!