Oracle中光标的使用和异常
上一篇 /
下一篇 2014-04-19 14:16:02
/ 个人分类:ORACLE
显式光标处理需四个 PL/SQL步骤:
cursor 光标名称 is 查询语句;
open 光标名称;
Fetch 光标名称 into 变量列表;
Close 光标名称;
1.没有参数的光标的使用
SQL> declare
cursor cl is select * from emp;
emp_row emp%rowtype;
begin
open cl;
loop
fetch cl into emp_row;
exit when cl%notfound;
dbms_output.put_line('员工的名称'|| emp_row.ename || '员工的部门'|| emp_row.deptno);
end loop;
close cl;
end;
/
员工的名称SMITH员工的部门20
员工的名称ALLEN员工的部门30
员工的名称WARD员工的部门30
员工的名称JONES员工的部门20
员工的名称MARTIN员工的部门30
员工的名称BLAKE员工的部门30
员工的名称CLARK员工的部门10
员工的名称SCOTT员工的部门20
员工的名称KING员工的部门10
员工的名称TURNER员工的部门30
员工的名称ADAMS员工的部门20
员工的名称JAMES员工的部门30
员工的名称FORD员工的部门20
员工的名称MILLER员工的部门10
PL/SQL procedure successfully completed
SQL> declare
cursor cl(emp_name varchar2) is select * from emp where ename=emp_name;
emp_row emp%rowtype;
begin
open cl('SMITH');
fetch cl into emp_row;
dbms_output.put_line('员工的名称'||emp_row.ename||'员工的工作'|| emp_row.job);
close cl;
end;
/
员工的名称SMITH员工的工作CLERK
部门编号为10的员工
SQL> declare
cursor cl(emp_deptno number) is select * from emp where deptno=emp_deptno;
emp_row emp%rowtype;
begin
open cl(10);
loop
fetch cl into emp_row;
exit when cl%notfound;
dbms_output.put_line( '员工的名称:'||emp_row.ename);
end loop;
close cl;
end;
/
员工的名称:CLARK
员工的名称:KING
员工的名称:MILLER
PL/SQL procedure successfully completed
除0的异常
SQL> declare
pnum number:=10;
begin
pnum:=pnum/0;
exception
when zero_divide then
dbms_output.put_line('除数不能为0');
end;
/
除数不能为0
PL/SQL procedure successfully completed
自定义的例外
SQL> declare
cursor cl(emp_no number) is select * from emp where empno=emp_no;
emprow emp%rowtype;
no_found exception;
begin
open cl(1000);
fetch cl into emprow;
if cl%notfound then raise no_found;
end if;
close cl;
exception
when no_found then
dbms_output.put_line('自己定义的意外');
end;
/
自己定义的意外
PL/SQL procedure successfully completed
收藏
举报
TAG: