PL/SQL LOOP Construct

Oracle提供三种样式的Loop结构

1. The Basic Loop

The BASIC loop repeats until a condition is met. Because the condition is tested at the end of the loop, the BASIC loop will always execute at least once.

A simple loop runs until you explicitly end the loop. The syntax for a simple loop is as follows:

LOOP

  [Sequence of statements]

EXIT [condition]

END LOOP;
 

To end the loop, you use either an EXIT or EXIT WHEN statement.

The EXIT statement ends a loop immediately.

EXIT WHEN statement ends a loop when a specified condition occurs.

Sample

Count up by hundreds until we get an error

SET ECHO ON
SET SERVEROUTPUT ON


DECLARE
  hundreds_counter  NUMBER(1,-2);
BEGIN
  hundreds_counter := 100;
  LOOP
    DBMS_OUTPUT.PUT_LINE(hundreds_counter);
    hundreds_counter := hundreds_counter + 100;
  END LOOP;
EXCEPTION
WHEN OTHERS THEN
  DBMS_OUTPUT.PUT_LINE('Done.');
END;
/

DECLARE
 i PLS_INTEGER := 1;
BEGIN
  LOOP
    i := i + 1;

    INSERT INTO loop_test VALUES (i);

    IF i > 99 THEN
      EXIT;
    END IF;
  END LOOP;
  COMMIT;
END;
/

SELECT * FROM loop_test;


2. The FOR Loop

The FOR loop repeats, incrementing or decrementing its internal counter until the counter reaches its pre-programmed limit, set by the lower_bound and higher_bound parameters.

-- incrementing
FOR <variable> IN <start_number> .. <end_number>
LOOP
  <code here>
END LOOP;

-- decrementing
FOR <variable> IN REVERSE <start_number> .. <end_number>
LOOP
  <code here>
END LOOP;

Sample

BEGIN
  FOR i IN 2000 .. 2100 LOOP
    INSERT INTO loop_test VALUES (i);
  END LOOP;
  COMMIT;
END;
/

SELECT * FROM loop_test;

BEGIN
  FOR i IN REVERSE 3000 .. 3100 LOOP
    INSERT INTO loop_test VALUES (i);
  END LOOP;
  COMMIT;
END;
/

SELECT * FROM loop_test;


3. The WHILE Loop

The WHILE loop repeats until a given condition is met. If the condition is not met it will repeat forever. If the condition is met or satisfied before the loop begins, it will not execute at all.

WHILE condition LOOP

  statement_1;

  statement_2;

  . . .

  statement_n;

END LOOP;

Example

DECLARE
 i PLS_INTEGER := 999;
BEGIN
  WHILE i < 1100 LOOP
    i := i + 1;

    INSERT INTO loop_test VALUES (i);
  END LOOP;
  COMMIT;
END;
/

SELECT * FROM loop_test;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值