MySQL中的循環可以通過使用循環控制語句來實現。MySQL支持以下幾種類型的循環:
WHILE condition DO
statements;
END WHILE;
例如:
SET @counter = 0;
WHILE @counter < 10 DO
SET @counter = @counter + 1;
SELECT @counter;
END WHILE;
REPEAT
statements;
UNTIL condition;
END REPEAT;
例如:
SET @counter = 0;
REPEAT
SET @counter = @counter + 1;
SELECT @counter;
UNTIL @counter >= 10 END REPEAT;
loop_label: LOOP
statements;
IF condition THEN
LEAVE loop_label;
END IF;
END LOOP;
例如:
SET @counter = 0;
loop_label: LOOP
SET @counter = @counter + 1;
SELECT @counter;
IF @counter >= 10 THEN
LEAVE loop_label;
END IF;
END LOOP;
在循環內部可以執行任意的SQL語句,包括查詢、插入、更新等操作。在循環過程中可以使用變量來進行計數、存儲結果等操作。