9.PL_SQL——PL_SQL中的循环控制语句

循环是指在程序中重复执行一条或多条语句、PL/SQL中的循环主要有三种:

                              1.Basic Loop

                              2. FORLoop

                              3.WHILE Loop

 

下面来逐一介绍这三种循环的用法。

 

一、BasicLoops

基本循环的格式如下:

             

              LOOP

                              statement1

                              ...

                              EXIT [WHENcondition];

              END LOOP;

             

这里的EXIT是用来退出循环的,如果没有EXIT,则会变成死循环。

 

下面来看一个小例子:

 

SQL>select location_id, city, country_id fromlocations where country_id = 'CA';

  LOCATION_ID CITY                    CO ----------- ------------------------------         1800 Toronto                 CA        1900 Whitehorse              CA -- 目前有两条记录


 

SQL>edit 

DECLARE         v_countryid     locations.country_id%TYPE :='CA';         v_loc_id        locations.location_id%TYPE;         v_counter       NUMBER(2) := 1;         v_new_city      locations.city%TYPE := 'Montreal'; BEGIN         SELECT MAX(location_id)         INTO v_loc_id         FROM locations         WHERE country_id =v_countryid;           LOOP             INSERT INTOlocations(location_id, city, country_id)             VALUES((v_loc_id +v_counter), v_new_city, v_countryid);             v_counter := v_counter+ 1;             EXIT WHEN v_counter> 3;            -- EXIT后面可以加上标签,来指定退出哪一层循环         END LOOP;           COMMIT; END; /

 

SQL>/ 

PL/SQL procedure successfully completed.

 

SQL>select location_id, city, country_id from locations where country_id = 'CA'; 

LOCATION_ID CITY                           CO ----------- ------------------------------ --        1800 Toronto                        CA        1900 Whitehorse                     CA        1901 Montreal                       CA        1902 Montreal                       CA        1903 Montreal                       CA             -- 执行了循环语句后,多了三条记录


 

                

二、WHILE循环

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。