控制结构
if
①if 条件 then 表达式 end if;
例:
begin
if 1= 1 then dbms_output.put_line('yes'); end if;
end;
/
② if 条件1 then 表达式1
elsif 条件2 then 表达式2
…
elsif 条件n then 表达式n
else 表达式 end if;
类似于 if 与 elseif 组合,注意这里是elsif
例:
declare
v_sal emp.sal%type;
v_result varchar2(8);
begin
select sal into v_sal from emp where empno = &empno;
if v_sal < 1500 then v_result := '低工资' ;
elsif v_sal < 3000 then v_result := '正常工资';
else v_result := '高工资'; end if;
dbms_output.put_line(v_result);
exception
when no_data_found then
dbms_output.put_line('员工不存在');
end;
/
case
① case 表达式
when 值1 then 表达式1
when 值2 then 表达式2
…
else 表达式
end case;
这样用法类似于开关结构(switch)就不举例了
② case
when 条件1 then 表达式1
when 条件2 then 表达式2
…
when 条件n then 表达式n
else 表达式
end case;
例:
declare
v_sal emp.sal%type;
v_result varchar2(8);
begin
select sal into v_sal from emp where empno = &empno;
case
when v_sal < 1500 then v_result := '低工资';
when v_sal > 1500 and v_sal <3000 then v_result := '一般工资';
else v_result := '高工资'; end case;
dbms_output.put_line(v_result);
exception
when no_data_found then
dbms_output.put_line('员工不存在');
end;
/
注:表达式中 的语句该加分号的一定要加!!!
循环结构
loop,while,for。以后都用1到100的和为例
①loop:
declare
v_sum int:= 0;
v_i int:= 1;
begin
loop
v_sum := v_sum + v_i;
v_i := v_i +1;
exit when v_i = 101;
end loop;
dbms_output.put_line(v_sum);
end;
/
exit when 后面表示退出循环的条件
②while
扫描二维码关注公众号,回复:
293677 查看本文章
declare
v_sum int:= 0;
v_i int:= 1;
begin
while v_i < 101 loop
v_sum := v_sum + v_i;
v_i := v_i +1;
end loop;
dbms_output.put_line(v_sum);
end;
/
③for
declare
v_sum int:= 0;
begin
for v_i in 1..100 loop
v_sum := v_sum + v_i;
end loop;
dbms_output.put_line(v_sum);
end;
/
for循环适合用于确定循环次数的情况,而while与loop适合不确定循环次数的情况。(老生常谈咯~~)