(注:主要摘自尚硅谷oracle教程笔记)
PL/SQL的流程控制语句,包括如下三类:
- 控制语句:IF 语句
- 循环语句:LOOP 语句,EXIT 语句
- 顺序语句:GOTO 语句,NULL 语句
条件语句
IF <布尔表达式> THEN
PL/SQL 和 SQL 语句;
END IF;
IF <布尔表达式> THEN
PL/SQL 和 SQL 语句;
ELSE
其他语句;
END IF;
IF <布尔表达式> THEN
PL/SQL 和 SQL 语句;
ELSIF <其他布尔表达式> THEN
其他语句;
ELSIF <其他布尔表达式> THEN
其他语句;
ELSE
其他语句;
END IF;
提示: ELSIF 不能写成 ELSEIF
示例:
使用 IF … THEN … ELSIF … THEN …ELSE … END IF
要求: 查询出 150号 员工的工资, 若其工资大于或等于 10000 则打印 ‘salary >= 10000’;
若在 5000 到 10000 之间, 则打印 ‘5000<= salary < 10000’; 否则打印 ‘salary < 5000’
(方法一)
declare
v_salary employees.salary%type;
begin
--通过 select ... into ... 语句为变量赋值
select salary into v_salary
from employees
where employee_id = 150;
dbms_output.put_line('salary: ' || v_salary);
-- 打印变量的值
if v_salary >= 10000 then
dbms_output.put_line('salary >= 10000');
elsif v_salary >= 5000 then
dbms_output.put_line('5000 <= salary < 10000');
else
dbms_output.put_line('salary < 5000');
end if;
(方法二)
declare
v_emp_name employees.last_name%type;
v_emp_sal employees.salary%type;
v_emp_sal_level varchar2(20);
begin
select last_name,salary into v_emp_name,v_emp_sal
from employees where employee_id = 150;
if(v_emp_sal >= 10000)
then v_emp_sal_level := 'salary >= 10000';
elsif(v_emp_sal >= 5000)
then v_emp_sal_level := '5000<= salary < 10000';
else v_emp_sal_level := 'salary < 5000';
end if;
dbms_output.put_line(
v_emp_name||','||v_emp_sal||','||v_emp_sal
);
end;
CASE 表达式
语法:
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE resultN+1]
END;
示例:
declare
v_sal employees.salary%type;
v_msg varchar2(50);
begin
select salary into v_sal
from employees
where employee_id = 150;
--case 不能向下面这样用
/*
case v_sal when salary >= 10000
then v_msg := '>=10000'
when salary >= 5000
then v_msg := '5000<= salary < 10000'
else v_msg := 'salary < 5000'
end;
*/
v_msg :=
case trunc(v_sal / 5000)
when 0 then 'salary < 5000'
when 1 then '5000<= salary < 10000'
else 'salary >= 10000'
end;
dbms_output.put_line(v_sal ||','||v_msg);
end;
使用 CASE … WHEN … THEN … ELSE … END
要求: 查询出 122 号员工的 JOB_ID, 若其值为
‘IT_PROG’, 则打印 ‘GRADE: A’;
‘AC_MGT’, 打印 ‘GRADE B’,
‘AC_ACCOUNT’, 打印 ‘GRADE C’;
否则打印 ‘GRADE D’
declare
--声明变量
v_grade char(1);
v_job_id employees.job_id%type;
begin
select job_id into v_job_id
from employees
where employee_id = 122;
dbms_output.put_line('job_id: ' || v_job_id);
--根据 v_job_id 的取值, 利用 case 字句为 v_grade 赋值
v_grade :=
case v_job_id when 'IT_PROG' then 'A'
when 'AC_MGT' then 'B'
when 'AC_ACCOUNT' then 'C'
else 'D'
end;
dbms_output.put_line('GRADE: ' || v_grade);
end;