Oracle PL/SQL之处理index不连续的table类型变量


测试代码:

  1. DECLARE  
  2.   TYPE list_of_names_t IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;  
  3.   happyfamily list_of_names_t;  
  4.   l_row       PLS_INTEGER;  
  5. BEGIN  
  6.   --build table data which index is not consecutive.  
  7.   happyfamily(2020202020) := 'Eli';  
  8.   happyfamily(-15070) := 'Steven';  
  9.   happyfamily(-90900) := 'Chris';  
  10.   happyfamily(-90899) := 'Chris90899';  
  11.   happyfamily(88) := 'Veva';  
  12.   
  13.   <<err1>>  
  14.   BEGIN  
  15.     dbms_output.put_line('=======err1========');  
  16.     --i is starting from 1 and increase one by one.  
  17.     FOR i IN 1 .. happyfamily.COUNT  
  18.     LOOP  
  19.       dbms_output.put_line(i);  
  20.       dbms_output.put_line(happyfamily(i));  
  21.     END LOOP;  
  22.   EXCEPTION  
  23.     WHEN OTHERS THEN  
  24.       dbms_output.put_line('err1=>' || SQLERRM);  
  25.   END;  
  26.   
  27.   <<err2>>  
  28.   BEGIN  
  29.     dbms_output.put_line('=======err2========');  
  30.     --i is starting from -90900 and increase one by one.  
  31.     FOR i IN happyfamily.FIRST .. happyfamily.LAST  
  32.     LOOP  
  33.       dbms_output.put_line(i);  
  34.       dbms_output.put_line(happyfamily(i));  
  35.     END LOOP;  
  36.   EXCEPTION  
  37.     WHEN OTHERS THEN  
  38.       dbms_output.put_line('err2=>' || SQLERRM);  
  39.   END;  
  40.   
  41.   <<pass>>  
  42.   BEGIN  
  43.     dbms_output.put_line('=======pass========');  
  44.     --i is starting from -90900 and increase discrete  
  45.     l_row := happyfamily.FIRST;  
  46.     WHILE (l_row IS NOT NULL)  
  47.     LOOP  
  48.       dbms_output.put_line(l_row);  
  49.       dbms_output.put_line(happyfamily(l_row));  
  50.       l_row := happyfamily.NEXT(l_row);  
  51.     END LOOP;  
  52.   EXCEPTION  
  53.     WHEN OTHERS THEN  
  54.       dbms_output.put_line('err3=>' || SQLERRM);  
  55.   END;  
  56. END;  

输出:

  1. =======err1========  
  2. 1  
  3. err1=>ORA-01403: no data found  
  4. =======err2========  
  5. -90900  
  6. Chris  
  7. -90899  
  8. Chris90899  
  9. -90898  
  10. err2=>ORA-01403: no data found  
  11. =======pass========  
  12. -90900  
  13. Chris  
  14. -90899  
  15. Chris90899  
  16. -15070  
  17. Steven  
  18. 88  
  19. Veva  
  20. 2020202020  
  21. Eli  

相关内容