/* *编写控制结构 */ --条件分支语句 --简单条件判断 DECLARE v_sal NUMBER(6,2); BEGIN select sal into v_sal from emp where lower(ename)=lower('&name'); if v_sal<2000 then update emp set sal=v_sal+200 where lower(ename)=lower('&name'); end if; end; select * from emp; --二重条件分支 --如果雇员补助不是0,则在原来的基础上增加100元,如果补助为0或NULL时,则设置其补助为200元 DECLARE v_comm NUMBER(6,2); BEGIN select comm into v_comm from emp where empno=&no; if v_comm <> 0 then update emp set comm=v_comm+100 where empno=&no; else update emp set comm=200 where empno=&no; end if; end; --多重条件分支 DECLARE v_job VARCHAR2(10); v_sal NUMBER(6,2); BEGIN SELECT JOB,SAL INTO v_job,v_sal from emp where empno=&no; if upper(v_job)=upper('president') then update emp set sal=v_sal+1000 where empno=&no; elsif upper(v_job)=upper('manager') then update emp set sal=v_sal+500 where empno=&no; else update emp set sal=v_sal+200 where empno=&no; end if; END; select * from emp; --CASE语句 --在CASE语句中使用单一选择符进行等值比较 DECLARE v_deptno emp.deptno%TYPE; begin v_deptno:=&no; case v_deptno when 1 then update emp set comm=100 where deptno=v_deptno; when 2 then update emp set comm=80 where deptno=v_deptno; when 3 then update emp set comm=50 where deptno=v_deptno; else dbms_output.put_line('不存在该部门'); end case; end; select * from emp; --在CASE语句中使用多种条件比较 DECLARE v_sal emp.sal%TYPE; v_ename emp.ename%TYPE; begin select ename,sal into v_ename,v_sal from emp where empno=&no; case when v_sal<1000 then update emp set comm=100 where ename=v_ename; when v_sal<2000 then update emp set comm=90 where ename=v_ename; when v_sal<6000 then update emp set comm=50 where ename=v_ename; end case; end; select * from emp; --循环语句 --基本循环 create table temp(cola int); DECLARE i INT:=1; begin LOOP insert into temp values(i); exit when i=10; i:=i+1; end loop; end; select * from temp; --WHILE循环 DECLARE i INT:=1; begin while i<=10 loop insert into temp values(i); i:=i+1; end loop; end; --FOR循环 begin for i in reverse 1..10 LOOP insert into temp values(i); end loop; end; --嵌套循环和标号 DECLARE result int; BEGIN <<outer>> for i in 1..100 loop <<inter>> for j in 1..100 loop result:=i*j; exit outer when result=1000; exit when result=500; end loop inner; dbms_output.put_line(result); end loop outer; dbms_output.put_line(result); end; --顺序控制语句 --GOTO DECLARE i INT:=1; begin LOOP INSERT INTO temp values(i); if i=10 then goto end_loop; end if; i:=i+1; end loop; <<end_loop>> dbms_output.put_line('循环结束'); END; --NULL --NULL语句不会执行任何操作,并且会直接将控制传递到下一条语句 --使用NULL语句的主要好处是可以提高PL/SQL程序的可读性 --如果雇员工资低于300,则将其补助设置为工资的10%,如果雇员工资高于3000,则不会执行任何操作(NULL) DECLARE v_sal emp.sal%TYPE; v_ename emp.ename%TYPE; BEGIN select ename,sal into v_ename,v_sal from emp where empno=&no; if v_sal<300 then update emp set comm=sal*0.1 where ename=v_ename; else null; end if; end; select * from emp;