一、了解动态 SQL 的语法
1,动态 SQL 是指在 PL/SQL 程序执行时生成的 SQL 语句,编译程序对动态 SQL 不做处理,而是在程序运行时动态构造语句、对语句进行语法分析并执行
2,DDL 语句命令和会话控制语句不能在 PL/SQL 中直接使用,但是可以通过动态 SQL 来执行
3,执行动态 SQL 的语法:
EXECUTE IMMEDIATE dynamic_sql_string [INTO define_variable_list] [USING bind_argument_list]; 例:
begin
create table t(tid number);
end; --这种程序包执行是会出错的,可以做出如下修改
begin
execute immediate 'create table t(tid number);
end;
二、错误处理
1,在运行程序时出现的错误叫做异常,发生异常后,语句将停止执行,控制权转移到 PL/SQL 块的异常处理部分
2,异常有两种类型:预定义异常;用户定义异常
2-1,预定义异常:当 PL/SQL 程序违反 Oracle 规则或超越系统限制时隐式引发;例:
declare
sname1 student.sname%type;
begin
select sname into sname1 from student where sno=5; --将 student 表中 sno=5 的行的 sname 列的数据赋值给变量
dbms_output.put_line(sname1)
exception --自定义异常处理
when no_data_found then --表示只要出现 oracle 定义的异常,就进行如下操作
dbms_output.put_line('没有这个学生存在');
end;
2-2,用户定义异常:用户可以在 PL/SQL 块的声明部分定义异常,自定义的异常通过 RAISE 语句显示引发;例:

declare
sbirth1 student.birthday%type;
excep1 exception; --声明一个异常
begin
select birthday into sbirth1 from student where sno=4;
if sbirth1 > to_date('20150101','yyyymmdd') then
raise excep1; --表明异常出现的条件:当取出的生日日期大于20150101时出现异常
else --如果没有异常出现
dbms_output.put_line('学生的年龄正常');
end if;
exception
where excep1 then --如果出现了异常,将执行如下操作
dbms_output.put_line('4号学生的年龄错误');
end;
3,引发应用程序错误
3-1,RAISE_APPLICATION_ERROR 过程
3-1-1,用于创建用户定义的错误信息
3-1-2,可以在可执行部分和异常处理部分使用
3-1-3,错误编号必须介于 -20000 和 -20999 之间
3-1-3,错误消息的长度可长达2048个字节
3-2,引发应用程序错误的语法:
RAISE_APPLICATION_ERROR(error_number,error_message); 例:
declare
sbirth1 student.birthday%type;
excep1 exception; --声明一个异常
begin
select birthday into sbirth1 from student where sno=4;
if sbirth1 > to_date('20150101','yyyymmdd') then
raise excep1; --表明异常出现的条件:当取出的生日日期大于20150101时出现异常
else --如果没有异常出现
dbms_output.put_line('学生的年龄正常');
end if;
exception
where excep1 then --如果出现了异常,将执行如下操作
dbms_output.put_line('4号学生的年龄错误');
raise_application_error(-20001,'年龄错误'); --显示的错误信息为:ORA-20001:年龄错误
end;
浙公网安备 33010602011771号