PL/SQL基础知识1(复合变量,异常处理)

pl/sql中除了varchar2,char,number,boolean.date等常用简单类型外还有表类型,记录类型

1.表类型(table):

其实表类型就相当于数组,而和数据库中存数据的表没啥关系.

语法:type type_name is table of scalar_datatype

[not null] index by binary_integer;

identifier type_name;

示例:

declare

type emp_table_type is table of emp.ename%type

index by binary_integer;

emp_table emp_table_type;

begin

select ename into emp_table(1) from emp where empno=6677;

select ename into emp_table(2) from emp where empno=7788;

dbms_out.put_line(emp_table(1));

dbms_out.put_line(emp_table(2));

end;

2.记录类型record:

record类型类似表中的一条记录,也就是一行.由不同的类型组成.当然record更复杂,除了可由不同的简单类型组成,还可由复合类型组成.比如嵌套record类型.

其实和c/c++中的结构体也差不多,只是里面只能有数据,不能有函数.

示例:

declare

type emp_record_type is record

(name varchar2(10),

num int);

emp_record emp_record_type;

begin

select ename,empno into emp_recordfrom emp where empno=7788;

dbms_out.put_line(emp_record.name);

dbms_out.put_line(emp_record.num);

end;

另外还有一种更简单的表示记录类型的方式.比如要用一个变量表示emp表中的一行.

declare

emp_record emp%rowtype;--表示emp表中一行

v_ename emp.ename%type;--表示与ename那一列类型相同的变量.是动态绑定的,如果表emp中ename的类型改变,v_ename跟着变.

begin

select* into emp_record from emp where empno=7788;

dbms_out.put_line(emp_record.ename);

dbms_out.put_line(emp_record.job);

end;

3.异常处理.

分为内部异常和自定义异常.

一.内部异常示例:

declare

v_text varchar2(10);

begin

select ename into v_text from emp where empno=123;

exception

when no_data_found then

dbms_out.put_line('no data exist!');

end;

二.自定义异常

1.用raise exception.

declare

e_noAuthority exception;

--PRAGMA EXCEPTION_INIT(e_noAuthority,-38008);

v_text varchar2(10);

begin

select ename into v_text from emp where empno=7788;

if(v_text='arwen') then

raise e_noAuthority;

end if;

exception

when e_noAuthority then

dbms_output.put_line('you have no authority to search');

end;

补充:在pl sql中我们能根据when e_noAuthority这样来捕捉异常.但如果是某个应用程序调用了这个存储过程.要想在应用程序的异常处理中处理错误该咋整.应用程序只能捕捉到错误编号.我们只要给异常绑定一个编号就行.在e_noAuthority exception;后面增加一行.PRAGMA EXCEPTION_INIT(e_noAuthority,-38008);这样在应用程序中可以捕捉到

ORA-38008这样的错误.

2.raise _application_error

declare

v_text varchar2(10);

--e_noAuthority exception

--PRAGMA EXCEPTION_INIT(e_noAuthority,-20212);

begin

select ename into v_text from emp where empno=123;

if(v_text='arwen') then

raise_application_error(-20212,'you have no authority to search this man');--错误代号只能取-20,000到-20,999.系统已经使用了20005到-20000的数字).

end if;

补充:加上PRAGMA EXCEPTION_INIT(e_noAuthority,-20212);的话就可以把错误编号与一个异常名字关联起来了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值