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中文網其他相關文章!