1. 程式人生 > >PL/SQL條件控制(IF)操作例項

PL/SQL條件控制(IF)操作例項

本部分主要講解PL/SQL條件控制語句的一下幾個:

語句描述
IF語句關聯的條件通過THEN和END IF關鍵字封閉的語句序列。如果條件為真,則語句被執行,如果條件為假或NULL,則IF語句什麼都不做
IF語句新增關鍵字ELSE後面的語句的替代序列。如果條件為假或NULL,語句則只有替換序列得到執行。它確保任一陳述的序列的被執行
可以使用一個IF-THEN或IF-THEN-ELSIF語句中的另一個IF-THEN或IF-THEN-ELSIF宣告

PL/SQL的原始碼操作例項:

-- Created on 2018/3/23 by E.WANG 
declare 
  --學生總分
  score integer;
begin
  /*
  score<60:為E 表示沒及格
  70>score>=60:為D 表示及格
  80>score>=70:為C 表示中等
  90>score>=80:為B,表示良好
  100>score>=90:為A,表示優秀
  score=100:為A+,表示優異
  */
  
  /*
  IF語句關聯的條件通過THEN和END IF關鍵字封閉的語句序列。
  如果條件為真,則語句被執行,如果條件為假或NULL,則IF語句什麼都不做
  */
  
  score:=-10;
  if score<0 then 
     dbms_output.put_line('Score is error!Please alter Score!');
  end if;
  
  /*
  IF語句新增關鍵字ELSE後面的語句的替代序列。
  如果條件為假或NULL,語句則只有替換序列得到執行。
  它確保任一陳述的序列的被執行
  */
  score:=101;
  if score between 0 and 100 then
     dbms_output.put_line('Score is right range!');
  else
     dbms_output.put_line('Please input again !');
  end if;
  
  /*
  它可以在幾個方案之間進行選擇
  */
  score:=78;
  if score<60 and score>=0 then
     dbms_output.put_line('The student mark is: E');
  elsif score>=60 and score<70 then
     dbms_output.put_line('The student mark is: D'); 
  elsif score>=70 and score<80 then
     dbms_output.put_line('The student mark is: C'); 
  elsif score>=80 and score<90 then
     dbms_output.put_line('The student mark is: C'); 
  elsif score>=90 and score<100 then
     dbms_output.put_line('The student mark is: A'); 
  elsif score=100 then
     dbms_output.put_line('The student mark is: A+'); 
  else
     dbms_output.put_line('Please input again !');
  end if;
  
  /*
  可以使用一個IF-THEN
  或IF-THEN-ELSIF語句中的
  另一個IF-THEN或IF-THEN-ELSIF宣告
  */
  
  score:=100;
  if score between 80 and 100 then
     if score=90 then
        dbms_output.put_line('The student mark is: A'); 
     else
        if score<90 and score>=80 then
           dbms_output.put_line('The student mark is: C');
        elsif score>=90 and score<100 then
           dbms_output.put_line('The student mark is: A'); 
        elsif score=100 then
          dbms_output.put_line('The student mark is: A+');   
        end if;
      end if;
  else
     dbms_output.put_line('Please input again !');
  end if;
  
end;

給出部分視窗截圖:


執行結果截圖: