oracle Loop循環示例


--loop循環用法 (輸出1到10)  
declare v_num number(2) := 0;  
begin   
  loop  
    v_num := v_num + 1;  
    exit when v_num > 10;  
    --上面退出循環也可以用下面3行  
     /* if(v_num > 9) then  
        exit;  
     end if;*/  
    dbms_output.put_line(v_num);   
  end loop;    
end;  
  
--while loop循環用法 (輸出1到10)  
declare v_num number(2) := 0;  
begin   
  while v_num < 10 loop  
     v_num := v_num + 1;  
     dbms_output.put_line(v_num);  
  end loop;    
end;  
  
--for loop循環用法1 (輸出1到10)  
declare v_num number(2) := 99;  
begin  
  for v_n in 1 .. v_num loop      
     exit when v_n > 10;  
     dbms_output.put_line(v_n);  
  end loop;  
end;  
  
--for loop循環用法2 (輸出某個表的序號、列數據)  
begin  
   for v_n in(select amount,rownum from tmp) loop   
      dbms_output.put_line(v_n.rownum || ' , ' || v_n.amount);  
   end loop;  
end;  
  
  
---個循環打印某個月日歷例子  
declare v_days number(2);   
        v_firstday number(2);  
        v_result varchar2(4000);  
        v_d varchar(100);  
        v_month date;  
begin  
   v_month := to_date('20170301','yyyymmdd');  
   v_result := to_char(v_month,'yyyy') || '年' || to_char(v_month,'mm') || '月' || chr(10) ||  '日 一 二 三 四 五 六' || chr(10);  
   select to_char(last_day(v_month), 'dd') into v_days from dual;--當月多少天  
   select to_char(trunc(v_month, 'mm'),'d') into v_firstday from dual;--當月第1天是星期幾:1-7      
   --1號所在星期幾的之前每一天補3個空格  
   for v_week in 1 .. v_firstday - 1  loop  
      exit when v_firstday < 2;  
      v_result := v_result || '   ';        
   end loop;  
   for v_date in 1 .. v_days loop  
      v_d := v_date;  
      if(length(v_date) = 1) then  
         v_d :=  ' '||v_date ;                  
      end if;  
      v_result := v_result || v_d || ' ';       
      if(mod(v_date + v_firstday, 7) = 1) then  
          v_result := v_result || ' ' || chr(10);         
      end if;  
   end loop;    
   dbms_output.put_line(v_result);  
end;  
/*  
運行結果:  
  
2017年03月  
日 一 二 三 四 五 六  
          1  2  3  4    
 5  6  7  8  9 10 11    
12 13 14 15 16 17 18    
19 20 21 22 23 24 25    
26 27 28 29 30 31   
*/  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM