1. 程式人生 > >PL/SQL程式設計的控制結構和迴圈結構

PL/SQL程式設計的控制結構和迴圈結構

控制結構

if

①if 條件 then 表示式 end if;
例:

begin
 if 1= 1 then dbms_output.put_line('yes'); end if;
end;
/

② if 條件1 then 表示式1
elsif 條件2 then 表示式2

elsif 條件n then 表示式n
else 表示式 end if;

類似於 if 與 elseif 組合,注意這裡是elsif
例:

declare
  v_sal emp.sal%type;
  v_result varchar2(8);
begin
select sal into v_sal from emp where empno = &empno; if v_sal < 1500 then v_result := '低工資' ; elsif v_sal < 3000 then v_result := '正常工資'; else v_result := '高工資'; end if; dbms_output.put_line(v_result); exception when no_data_found then dbms_output.put_line('員工不存在'); end; /

case

① case 表示式
when 值1 then 表示式1
when 值2 then 表示式2

else 表示式
end case;
這樣用法類似於開關結構(switch)就不舉例了

② case
when 條件1 then 表示式1
when 條件2 then 表示式2

when 條件n then 表示式n
else 表示式
end case;

例:

declare
  v_sal emp.sal%type;
  v_result varchar2(8
); begin select sal into v_sal from emp where empno = &empno; case when v_sal < 1500 then v_result := '低工資'; when v_sal > 1500 and v_sal <3000 then v_result := '一般工資'; else v_result := '高工資'; end case; dbms_output.put_line(v_result); exception when no_data_found then dbms_output.put_line('員工不存在'); end; /

注:表示式中 的語句該加分號的一定要加!!!

迴圈結構

loop,while,for。以後都用1到100的和為例

①loop:

declare
  v_sum int:= 0;
  v_i int:= 1;
begin
  loop
    v_sum := v_sum + v_i;
    v_i := v_i +1;
    exit when v_i = 101;
  end loop;
dbms_output.put_line(v_sum);
end;
/

exit when 後面表示退出迴圈的條件

②while

declare
  v_sum int:= 0;
  v_i int:= 1;
begin
  while v_i < 101 loop
    v_sum := v_sum + v_i;
    v_i := v_i +1;
  end loop;
dbms_output.put_line(v_sum);
end;
/

③for

declare
  v_sum int:= 0;
begin
  for v_i in 1..100 loop
    v_sum := v_sum + v_i;
  end loop;
dbms_output.put_line(v_sum);
end;
/

for迴圈適合用於確定迴圈次數的情況,而while與loop適合不確定迴圈次數的情況。(老生常談咯~~)