-- 游标(光标cursor)
--在写Java程序中有集合的概念, 那么在pl/sql中也会用到多条记录, 这时候我们就要用到游标, 游标可以存储查询返回的多条数据。
-- 语法:cursor 游标名(参数 数据类型,参数 数据类型) is select 语句;
-- 列如 cursor c1 is select ename from emp;
-- 游标使用步骤
-- 打开游标:open c1
-- 取一行游标值 fetch c1 into pjob;(取一行数据到变量中)
-- 关闭游标 close c1
-- 游标结束方式 exit when c1%notfound
-- 查询姓名和工资
declare
cursor vrows is select * from emp;
vrow emp%Rowtype;
begin
open vrows;
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename||' '||'工资:'||vrow.sal);
end loop;
close vrows;
end;
-- 指定部门下的员工工资
declare
cursor deptSal(dno number) is select * from emp where deptno=dno;
dep emp%rowtype;
begin
open deptSal(10);
loop
fetch deptSal into dep;
exit when deptSal%notfound;
dbms_output.put_line('员工姓名:'||dep.ename||' '||'工资:'||dep.sal);
end loop;
close deptSal;
end;
-- 引用系统游标
declare
vrows sys_refcursor; -- 引用系统游标
vrow emp%rowtype; -- 记录一行数据
begin
open vrows for select * from emp;
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename||' '||'工资:'||vrow.sal);
end loop;
close vrows;
end;
-- 使用for循环遍历游标
declare
-- 申明游标
cursor vrows is select * from emp;
begin
for vrow in vrows loop
dbms_output.put_line('姓名为:'||vrow.ename||'工资为:'||vrow.sal);
end loop;
end;
-- 按员工的工种长工资,总裁1000元,经理长800元其, 他人员长400元
declare
cursor vrows is select * from emp;
vrow emp%rowtype;
begin
open vrows;
loop
fetch vrows into vrow;
exit when vrows%notfound;
if vrow.job='PRESIDENT' then
update emp set sal=sal+1000 where empno=vrow.empno;
elsif vrow.job='MANAGER' then
update emp set sal=sal+800 where empno=vrow.empno;
else
update emp set sal=sal+400 where empno=vrow.empno;
end if;
dbms_output.put_line('姓名为:'||vrow.ename||'工资为:'||vrow.sal);
end loop;
close vrows;
end;
Oracle游标的基本用法详解
最新推荐文章于 2024-05-05 02:18:45 发布