Oracle-34-if語句、case語句、loop迴圈、while迴圈、for迴圈

來源:互聯網
上載者:User

標籤:

一、IF語句

在PL/SQL中,if, then, else, elsif, endif等關鍵字用來執行條件邏輯

文法格式:


if  條件1 then

      語句1

elsif  條件2 then

      語句2

else

      語句3

end if;

 

例1:練習if結構

解:注意中的程式:




二、case語句

文法結構:


case 變數

when 值1 then語句1;

when 值2 then語句2;

when 值3 then語句3;

……

when 值n then語句n;

[else 語句]

end case;


其中[else 語句]可寫可不寫。

 

例2:練習case語句

解:注意中的程式:




例3:練習case語句

解:輸出目前時間是星期幾,首先查看當前系統時間是一周的第幾天:




其中to_char(sysdate,’d’)是將當前系統時間格式化,只顯示天,Oracle由於是老外開發的資料庫系統,所以一周第1天是星期日,第2天是星期一,……,第7天是星期六,所以程式如下:




三、迴圈

1.LOOP迴圈的文法格式:


loop

      迴圈語句

end loop;

 

比如:

counter := 0;

loop

      counter := counter + 1;

      exit when counter = 5;

end loop;

 

例4:練習loop迴圈

解:注意中的程式:




發現沒有輸出結果到控制台,那麼可用如下方式添加代碼




輸出結果:




2.WHILE迴圈文法格式:


while 條件 loop

      語句

end loop

 

比如:

counter := 0;

while counter < 6 loop

counter := counter +1;

end loop;

 

例5:練習while迴圈

解:注意中的程式:




3.FOR迴圈文法格式


for 變數 in [revers]變數初值..變數迴圈結束值 loop

      語句

end loop;

 

比如:

for iin 1..10 loop

      dbms_output.put_line(‘i = ‘ + i);

end loop;

 

例6:練習for迴圈

解:注意中的程式:




例7:展示99乘法表

解:注意中的程式:




其中dbms_out.put()是輸出語句但是不換行,如果dbms_output.put_line()是輸出語句並換行,所以中第7行在裡層迴圈結束後列印null,目的實則是換行。

 

例8:請編寫PL/SQL程式,將查詢student表中sno,sname放入記錄表變數中,並將記錄表變數中的資料列印出來。

解:注意中的程式:




其中第6行是將記錄t_record中的給記錄表t_tab,即t_record中有id和name,那麼t_tab中也有。

Oracle-34-if語句、case語句、loop迴圈、while迴圈、for迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.