MySQL 不提供用於迭代表行的內建循環機制。但是,有多種方法可以實現此功能:
此方法涉及使用遊標來瀏覽表行。遊標充當指向表中特定行的指標。以下程式碼片段示範如何使用遊標:
DROP PROCEDURE IF EXISTS loop_through_rows; DELIMITER ;; CREATE PROCEDURE loop_through_rows() BEGIN DECLARE cursor_id INT; DECLARE cursor_val VARCHAR; DECLARE done INT DEFAULT FALSE; DECLARE cursor CURSOR FOR SELECT ID, VAL FROM table_A; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cursor; read_loop: LOOP FETCH cursor INTO cursor_id, cursor_val; IF done THEN LEAVE read_loop; END IF; -- Perform operations on cursor_id and cursor_val END LOOP; CLOSE cursor; END; ;; DELIMITER ;
此方法利用 WHILE 迴圈來重複擷取和處理行。循環繼續,直到處理完所有行。以下程式碼說明了此方法:
SET @record = 0; SET @last_record = (SELECT COUNT(*) FROM table_A); WHILE @record < @last_record DO -- Perform operations on the current @record SET @record = @record + 1; END WHILE;
您可以建立一個封裝循環功能的預存程序。這允許您執行過程並迭代行。
DROP PROCEDURE IF EXISTS loop_rows; DELIMITER ;; CREATE PROCEDURE loop_rows(IN table_name VARCHAR(255)) BEGIN SET @record = 0; SET @last_record = (SELECT COUNT(*) FROM table_name); WHILE @record < @last_record DO -- Perform operations on the current @record SET @record = @record + 1; END WHILE; END; ;; DELIMITER ;
以上是如何遍歷 MySQL 中表格的所有行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!