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_record from 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);的話就可以把錯誤編號與一個異常名字關聯起來了.