Oracle(PLSQL)入门学习八
学习视频:https://www.bilibili.com/video/BV1tJ411r7EC?p=75
游标cursor:用于存放多条数据的容器。需要开始open和关闭close。游标下移使用“fetch...into...”。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。declare cursor myCursor is select * from emp; yb myCursor%rowtype; begin open myCursor; for i in 1 .. 3 loop fetch myCursor into yb; dbms_output.put_line(yb.empno || yb.ename); end loop; close myCursor; end;
使用%found和%notfound属性判断游标是否有值,使用这两个属性的前提是游标必须经过下移。
declare cursor myCursor is select * from emp; yb myCursor%rowtype; begin open myCursor; loop fetch myCursor into yb; dbms_output.put_line(yb.empno || '-' || yb.ename); exit when myCursor%notfound; end loop; close myCursor; end;
declare cursor myCursor is select * from emp; yb myCursor%rowtype; begin open myCursor; fetch myCursor into yb; --游标必须先经过下移,才能使用%found和%notfound属性 while myCursor%found loop fetch myCursor into yb; dbms_output.put_line(yb.empno || '-' || yb.ename); end loop; close myCursor; end;
智能游标:变量定义、自动开关、自动下移。
--智能游标 --变量自动定义 --游标自动开 --游标自动下移 --自动关闭 declare cursor myCursor is select * from emp; begin for employee in myCursor loop dbms_output.put_line(employee.empno || '-' || employee.ename); end loop; end;
异常:无法预测的程序错误。
declare employee emp%rowtype; begin select * into employee from emp where empno = 70369; exception when no_data_found then dbms_output.put_line('找不到数据'); when others then dbms_output.put_line('默认异常,,,'); end;
存储过程:远程发送存储过程名,不需要发送具体的sql,避免发送过程中被截取、篡改sql。优点:提高效率,且更加安全。
create or replace procedure getmax(x number, y number) is begin if x > y then dbms_output.put_line(x); else dbms_output.put_line(y); end if; end; call getmax(10,12); exec getmax(11,12); execute getmax(45,56);
调用存储过程三种方法call、exec、execute。
存储过程参数模式:in表示只读,out表示只写,in out表示可读可写。
--参数变量 参数模式 参数类型。 默认模式为in。 create or replace procedure getmax(x in number, y in number,z out number) is begin if x > y then z:=x; else z:=y; end if; end; declare max_result number; begin getmax(89, 85, max_result); dbms_output.put_line(max_result); end;
函数:和存储过程不同的是可以返回值。
create or replace function fgetmax(x number, y number) return number is begin if y > x then return y; else return x; end if; end; / select fgetmax(45,44) from dual;

更多精彩