PL_SQL基礎--續二

PL_SQL的分支和循環:

 

 declare
  v_sal emp.sal%type;
 begin
  select sal into v_sal from emp
   where empno = 7369;
  if(sal < 1200) then
   dbms_output.put_line('low');
  elsif(v_sal<2000) then  --注意elsif拼寫,少一個e.
   dbms_output.put_line('middle');
  else   ---注意else後面不跟then
   dbms_output.put_line('high');
  end if;  ---endif後面要有分號(;)
 end;

 

循環:
 ---相當於do-while循環
 declare
  i binary_integer := 1;
 begin
  loop   ---循環開始
   dbms_output.put_line(i);
   i := i + 1;
   exit when(i >=11); ---跳出循環的條件
  end loop;  --循環結束
 end;

 --相當於while循環
 declare
  j binary_integer := 1;
 begin
  while j < 11 loop
   dbms_output.put_line(j);
   j := j+1;
  end loop;
 end;
 
 ---相當於for循環
 begin
  for k in 1..10 loop
   dbms_output.put_line(k);
  end loop;

  for k in reverse 1..10 loop ---reverse逆序循環 從10到1.
   dbms_output.put_line(k);
  end loop;
 end;

 

錯誤處理:
 declare
  v_temp number(4);
 begin
  select empno into v_temp from emp where deptno = 10;
 exception
  when too_many_rows then
   dbms_output.put_line('太多記錄了');
  when no_data_found then
   dbms_output.put_line('沒數據');
  when others then
   dbms_output.put_line('error');
 end;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章