Oracle笔记:pl/sql控制结构

1.条件分支语句
  1)if……then 例:
    --编写一个过程,可以输入一个雇员名,如果该雇员的工资低于2000,则给该雇员工资增加10%
    create or replace procedure update_sal(sname varchar2) is
    v_sal emp.sal%type;
    begin
      select sal into v_sal from emp where ename=sname;
      if v_sal<2000 then
        update emp set sal=sal*1.1 where ename=sname;
      end if;
    end; 

  2)if……then……else 例:
    --编写一个过程,可以输入一个雇员名,如果该雇员的补助不为0,就在原来的基础上增加100,如果补助为0就把补助设为200
    create or replace procedure update_comm(sname varchar2) is
    v_comm emp.comm%type;
    begin
      select comm into v_comm from emp where ename=sname;
      if v_comm<>0 then
        update emp set comm=comm+100 where ename=sname;
      else
        update emp set comm=200 where ename=sname;
      end if;
    end; 

  3)if……then……elsif……else 例:
    --编写一个过程,可以输入一个雇员编号,如果该雇员的职位是PRESIDENT,则将他的工资增加1000;
    --如果该雇员的职位是MANAGER,则将他的工资增加500;其他职位的工资增加200
    create or replace procedure update_sal(sno number) is
    v_job emp.job%type;
    begin
      select job into v_job from emp where empno=sno;
      if v_job='PRESIDENT'then
         update emp set sal=sal+1000 where empno=sno;
      elsif v_job='MANAGER' then
         update emp set sal=sal+500 where empno=sno;
      else
         update emp set sal=sal+200 where empno=sno;
      end if;
    end; 

2.循环语句
 1) loop: pl/sql中最简单的循环,至少会被执行一次,例:
  --有一张users表,有用户ID和用户名两个字段。
  --编写一个过程,可输入用户名,并循环添加10个用户到users表中,用户编号从1开始增加。
  create or replace procedure add_users(sName varchar2) is
  v_no number:=1;
  begin
    loop
      insert into users values(v_no,sName);
       --判断是否要退出循环
      exit when v_no=10;
      v_no:=v_no+1;
    end loop;
  end;

 2)where 例:
 --编写一个过程,可输入用户名,并循环添加10个用户到users表中,用户编号从11开始增加。
 create or replace procedure add_users(sName varchar2) is
 v_no number:=11;
 begin
   while v_no<=20 loop
     insert into users values(v_no,sName);
     v_no:=v_no+1;
   end loop;
 end;

  3) for

3. 顺序控制语句
  1) goto

  2) null:null语句不会执行任何操作,并且会直接将控制传递到下一条语句,使用null语句的主要好处是可以提高pl/sql的可读性。

原文地址:https://www.cnblogs.com/testing/p/3003293.html