当前位置: 代码迷 >> SQL >> PLSQL开发笔记和小结(3)——PLSQL流程控制和错误处理(转载)
  详细解决方案

PLSQL开发笔记和小结(3)——PLSQL流程控制和错误处理(转载)

热度:9   发布时间:2016-05-05 12:13:34.0
PLSQL开发笔记和小结(3)——PLSQL流程控制和异常处理(转载)

*****************************************

???PLSQL流程控制

*****************************************

if判断

declare

??????? v_name varchar2(20):='cheng';

begin

???? if v_name='0701' then

??????? dbms_output.put_line('0701');

???? elsif v_name='cheng' then

??????? dbms_output.put_line('cheng');

???? else

??????? dbms_output.put_line('false');

???? end if;

end;

loop循环,注意退出exit是退出循环,而不是退出整个代码块

declare

?????? v_i binary_integer:=1;

begin

???? loop

???????? if v_i>10 then

??????????? exit;

???????? end if;

???????? v_i:=v_i+1;

???????? dbms_output.put_line('hehe');

???? end loop;

?????dbms_output.put_line('over');

end;

loop简化写法

declare

?????? v_i binary_integer:=1;

begin

???? loop

???????? exit when v_i>10;

???????? v_i :=v_i+1;

???????? dbms_output.put_line('hehe');

???? end loop;

?????dbms_output.put_line('over');

end;

while循环

declare

?????? v_i binary_integer:=1;

begin

?????? while v_i<=10 loop

???????????? dbms_output.put_line('hello'||v_i);

???????????? v_i:=v_i+1;

?????? end loop;

?????? dbms_output.put_line('over');

end;

do…while循环

declare

?????? v_i binary_integer:=1;

begin

?????? loop

???????????? dbms_output.put_line('hello'||v_i);

???????????? v_i:=v_i+1;

?????????????? exit when(v_i>10);--v_i>10时,退出循环

?????? end loop;

?????? dbms_output.put_line('over');

end;

for循环,注意不需要声明变量

begin

???? for v_i in 1..10 loop

???????? dbms_output.put_line('hello'||v_i);

???? end loop;

?????dbms_output.put_line('over');

end;

*****************************************

PLSQL异常处理

*****************************************

1、声明异常

?异常名 exception

2、抛出异常

?raise异常名

3、处理异常

?抛出异常后的逻辑代码不会被继续执行

异常的定义使用

??? ―――――――――――――――――――――――――――――――――――――

??? begin

???? ???? dbms_output.put_line(1/0);

??? exception

??????????? when others then

??????????????? dbms_output.put_line('error');

end;

?

??? declare

??????????? e_myException exception;

??? begin

??????????? dbms_output.put_line('hello');

??????????? raise e_myException; --raise抛出异常,用此关键字,抛出后转到自定义的e_myException ,执行其里面的putline函数后,再跳到end处,结束PL/SQL块,raise接下面的2句不会继续执行。

??????????? dbms_output.put_line('world');

??????????? dbms_output.put_line(1/0);

??? exception

??????????? when e_myException then

??????????????? dbms_output.put_line(sqlcode); --当前会话执行状态,错误编码

??????????????? dbms_output.put_line(sqlerrm); --当前错误信息

??????????????? dbms_output.put_line('my error');

??????????? when others then

??????????????? dbms_output.put_line('error');

??? end;

?

转载自:http://www.blogjava.net/cheneyfree/archive/2008/07/19/216090.html?

  相关解决方案