大家好,我在看oracle PL/SQL programming 有关LOOP循环的时候遇到这个问题,这段代码书上说违背了单一出口的原则,我也觉得很有道理,但是书上给出的解决办法没有明说,只是给了一个建议,我想问的是到底应该怎么改才算符合单一出口 1   DECLARE
 2      CURSOR occupancy_cur IS
 3         SELECT pet_id, room_number
 4           FROM occupancy WHERE occupied_dt = TRUNC (SYSDATE);
 5      pet_count INTEGER := 0;
 6   BEGIN
 7      FOR occupancy_rec IN occupancy_cur
 8      LOOP
 9         update_bill
10             (occupancy_rec.pet_id, occupancy_rec.room_number);
11          pet_count := pet_count + 1;
12          EXIT WHEN pet_count >= :GLOBAL.max_pets;
13       END LOOP;
14    END;
这是原文:The FOR loop explicitly states: "I am going to execute the body of this loop n times" (where n is a number in a numeric FOR loop, or the number of records in a cursor FOR loop). An EXIT inside the FOR loop (line 12) short-circuits this logic. The result is code that's difficult to follow and debug.If you need to terminate a loop based on information fetched by the cursor FOR loop, you should use a WHILE loop or a simple loop in its place. Then the structure of the code will more clearly state your intentions.

解决方案 »

  1.   

    SELECT pet_id, room_number
     FROM occupancy WHERE occupied_dt = TRUNC (SYSDATE) and rownum<:GLOBAL.max_pets+1;
      

  2.   


       DECLARE
          CURSOR occupancy_cur IS
             SELECT pet_id, room_number
               FROM occupancy WHERE occupied_dt = TRUNC (SYSDATE);
          row_occupancy_cur occupancy_cur%rowtype;
          pet_count INTEGER := 0;
        BEGIN
           open occupancy_cur;
           LOOP
              FETCH occupancy_cur INTO row_occupancy_cur;
              update_bill
                 (row_occupancy_cur.pet_id, row_occupancy_cur.room_number);
              pet_count := pet_count + 1;
              EXIT WHEN pet_count >= :GLOBAL.max_pets;
           END LOOP;
        END;
    有一点值得注意,要存在EXIT WHEN pet_count >= :GLOBAL.max_pets;
    不然就是死循环
      

  3.   

    谢谢啊,不过我是想问按照原文的意思,应该怎么写,
    这一句:If you need to terminate a loop based on information fetched by the cursor FOR loop, you should use a WHILE loop or a simple loop in its place.