在 MySQL 預存程序中執行動態查詢並擷取輸出
在 MySQL 中,預存程序可讓您有效率地執行複雜的操作。一個常見的場景是根據輸入參數動態產生查詢並將結果檢索到變數中。
要實現此目的,您可以利用準備好的語句和輸出參數。讓我們考慮以下預存程序:
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 參數中,您可以使用以下方法:
CREATE TABLE table1( column1 VARCHAR(255) DEFAULT NULL, column2 VARCHAR(255) DEFAULT NULL, column3 VARCHAR(255) DEFAULT NULL ); INSERT INTO table1 VALUES ('1', 'value1', 'value2'), ('2', 'value3', 'value4'); DELIMITER $$ CREATE PROCEDURE procedure1(IN Param1 VARCHAR(255), OUT Param2 VARCHAR(255), OUT Param3 VARCHAR(255)) BEGIN SET @c2 = ''; SET @c3 = ''; SET @query = 'SELECT column2, column3 INTO @c2, @c3 FROM table1 WHERE column1 = ?'; PREPARE stmt FROM @query; SET @c1 = Param1; EXECUTE stmt USING @c1; DEALLOCATE PREPARE stmt; SET Param2 = @c2; SET Param3 = @c3; END$$ DELIMITER ; -- Call procedure and use variables SET @Param1 = 2; SET @Param2 = ''; SET @Param3 = ''; CALL procedure1(@Param1, @Param2, @Param3); SELECT @Param2, @Param3;
在此範例中:
透過利用此技術,您可以將動態產生的查詢的輸出檢索到變數中在 MySQL 預存程序中。
以上是如何從 MySQL 預存程序中的動態查詢檢索輸出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!