Oracle中也有选择结构和循环结构,其大概的逻辑和Java等语言是相通的,只有些许的语法有所不同,如果有兴趣的可以对照学习Java程序:顺序,选择,循环以及另外一篇oracle循环。现在就来看看Oracle中的选择结构吧。
一.选择结构
1.if语句
①If 条件 then //执行语句 end if;
②if 条件 then //执行语句1 else //执行语句2 end if;
③if 条件1 then //执行语句1 elsif 条件2 then //执行语句2 else //执行语句3 end if;
其实三个语句语法都差不多,自行根据需要判断的数据来选择是哪一种if语句的结构.
ex1:在scott模式下,查询emp表中编号为7788的员工工资(elsif)
declare
V_saly scott.emp.sal%type;
begin
select emp.sal into V_saly from emp where empno=7788;
if V_saly<=2000 then dbms_output.put_line('这工资不说了,说多了都是泪!');
elsif V_saly<=3000 then dbms_output.put_line('这工资可以养活自己了!');
elsif V_saly<=4000 then dbms_output.put_line('这工资可以养活自己,还可以养条狗!');
elsif V_saly<=5000 then dbms_output.put_line('这工资可以考虑交个女朋友');
else dbms_output.put_line('这工资比较高大上');
end if;
end;
ex2:根据考试成绩判断等级(elsif case)
declare
V_score number :=(&分数);
begin
if V_score>=90 then dbms_output.put_line('优');
elsif V_score>=80 then dbms_output.put_line('良');
elsif V_score>=70 then dbms_output.put_line('中');
elsif V_score>=60 then dbms_output.put_line('刚及格');
else dbms_output.put_line('不及格');
end if;
end;
2.case语句
case selectorwhen expression_1 then //语句1;end case;
ex1:scott模式下,查询emp表中编号为7788的员工职务(case)
declare
V_job scott.emp.job%type;
begin
select emp.job into V_job from emp where empno=7788;
case V_job
when 'PRESIDENT'then dbms_output.put_line('雇员职务:总裁');
when 'MANAGER'then dbms_output.put_line('雇员职务:经理');
when 'SALESMAN'then dbms_output.put_line('雇员职务:推销员');
when 'ANALYST'then dbms_output.put_line('雇员职务:系统分析员');
when 'ANALYST'then dbms_output.put_line('雇员职务:职员');
else dbms_output.put_line('雇员职务:未知');
end case;
end;
ex2:将上面i的f语句的eg2改为case语句
declare
V_score number :=(&分数);
begin
case
when V_score>=90 then dbms_output.put_line('优');
when V_score>=80 then dbms_output.put_line('良');
when V_score>=70 then dbms_output.put_line('中');
when V_score>=60 then dbms_output.put_line('刚及格');
else dbms_output.put_line('不及格');
end case;
end;
3.搜索式case
case when search_condition_1 then //语句1;
……..
when search_condition_N then //语句n;
end case;
ex:把case语句的eg1改成搜索式case
declare
V_job scott.emp.job%type;
begin
select emp.job into V_job from emp where empno=7788;
case
when V_job= 'PRESIDENT'then dbms_output.put_line('雇员职务:总裁');
when V_job='MANAGER'then dbms_output.put_line('雇员职务:经理');
when V_job='SALESMAN'then dbms_output.put_line('雇员职务:推销员');
when V_job='ANALYST'then dbms_output.put_line('雇员职务:系统分析员');
when V_job='CLERK'then dbms_output.put_line('雇员职务:职员');
else dbms_output.put_line('雇员职务:未知');
end case;
end;