本文共 3454 字,大约阅读时间需要 11 分钟。
游标是PL/SQL中用来操作数据库结果集的重要工具,类似于JDBC中的ResultSet。它允许我们逐行处理数据库中的数据。
cursor 游标名 [(参数名,数据类型)] is select 语句;
打开游标并执行查询
open 游标名;
从游标中获取数据
fetch 游标名 into 变量名;
关闭游标
close 游标名;
处理游标结束
exit when 游标名%notfound;
declare cursor vrows is select * from emp; vrow emp%rowtype;begin open vrows; loop fetch vrows into vrow; dbms_output.put_line(vrow.ename); exit when vrows%notfound; close vrows;end;
declare cursor vrows(vdeptno number) is select * from emp where deptno = vdeptno; vrow emp%rowtype;begin open vrows(20); loop fetch vrows into vrow; dbms_output.put_line(vrow.ename); exit when vrows%notfound; close vrows;end;
declare cursor vrows is select * from emp;begin for vrow in vrows loop dbms_output.put_line('姓名:'||vrow.ename||' 工资:'||vrow.sal); end loop;end; -- 声明一个游标vrows sys_refcursor;-- 打开游标并执行查询open vrows for select * from emp;
在PL/SQL中,异常是用来处理数据库操作中可能出现的错误。常见的异常类型包括:
declare i number; vrow emp%rowtype;begin -- 例子 select * into vrow from emp where empno=1234567;exception when too_many_rows then dbms_output.put_line('找到了多行记录,但是赋值给了一行'); when no_data_found then dbms_output.put_line('没有找到记录'); when value_error then dbms_output.put_line('类型转换错误'); when zero_divide then dbms_output.put_line('除零错误'); when others then dbms_output.put_line('未知错误');end; -- 声明自定义异常no_emp_found exception;-- 抛出自定义异常raise no_emp_found;
存储过程是将一段PL/SQL代码封装到数据库中,方便复用和管理。常见用途包括:
create [or replace] procedure 存储过程名称(参数名 参数类型) is begin -- 业务逻辑 end;
create or replace procedure proc_updatesal(vempno in number, vcount in number) is vsal number;begin -- 查询涨薪前的工资 select sal into vsal from emp where empno = vempno; -- 打印涨薪前的工资 dbms_output.put_line('涨薪前:'||vsal); -- 涨薪 update emp set sal = vsal + vcount where empno = vempno; -- 打印涨薪后的工资 dbms_output.put_line('涨薪后:'||(vsal + vcount)); -- 提交事务 commit;end; -- 调用存储过程call proc_updatesal(7369, 10);
函数是将一段PL/SQL代码封装到数据库中,方便调用。与存储过程不同,函数有返回值。
create [or replace] function 函数名称(参数名 参数类型) return 返回类型 is begin -- 业务逻辑 end;
create or replace function func_getyearsal(vempno number) return number is vyearsal number;begin select sal*12 + nvl(comm, 0) into vyearsal from emp where empno = vempno; return vyearsal;end;
-- 调用函数declare yearsal number;begin yearsal := func_getyearsal(7369); dbms_output.put_line('年薪:'||yearsal);end; 触发器是数据库执行insert、update、delete操作时,可以自动执行一段PL/SQL代码。
create [or replace] trigger 触发器名称 before|after insert|update|delete on 表名 [for each row] is begin -- 业务逻辑 end;
create or replace trigger tri_checkbeforeinsert beforeinsert on emp is vday varchar2(20);begin select trim(to_char(sysdate, 'day')) into vday from dual; if vday = 'saturday' then raise_application_error(-20000, '老板周六不在,不能插入数据!'); end if;end;
create or replace trigger tri_test3 beforeupdate on emp for each row is begin dbms_output.put_line('行级触发器:'||:new.sal||' 旧的记录:'||:old.sal); end;update emp set sal = sal - 10; 通过以上内容,可以清晰地了解PL/SQL中的游标、异常、存储过程、函数和触发器的使用方法及其各自的特点。
转载地址:http://pphwz.baihongyu.com/