/*
遊標
CURSOR 遊標名[(參數1 數據類型[,參數2 數據類型...])] IS SELECT語句;
開發步驟
聲明遊標
打開遊標 open 遊標名
提取數據 fetch 遊標名 into 記錄名(變量)
遊標名%found 發現記錄
遊標名%notfound 沒有發現數據
關閉遊標 close 遊標名
系統引用遊標
聲明遊標 遊標名 sys_refcursor;
打開遊標 open 遊標名 for select *
提取數據
關閉遊標
*/
-- 查詢emp所有數據,不帶參數
declare
cursor ybs is select * from emp;
yb emp%rowtype;
begin
open ybs;
loop
fetch ybs into yb;
exit when ybs%notfound;
dbms_output.put_line(yb.ename||'.'||yb.job||'.'||yb.sal);
end loop;
close ybs;
end;
-- 查詢部門爲20 帶參數
declare
cursor ybs(dno number) is select * from emp where deptno = dno;
yb emp%rowtype;
begin
open ybs(20); -- 開啓遊標,指定查詢20號
loop
fetch ybs into yb;
exit when ybs%notfound;
dbms_output.put_line(yb.ename||'.'||yb.job||'.'||yb.sal);
end loop;
close ybs;
end;
-- 使用系統引用遊標
declare
ybs sys_refcursor;
yb emp%rowtype;
begin
open ybs for select * from emp;
loop
fetch ybs into yb;
exit when ybs%notfound;
dbms_output.put_line(yb.job||'.'||yb.sal);
end loop;
close ybs;
end;
-- 使用for循環 接收遊標數據
declare
cursor ybs(dno number) is select * from emp where deptno = dno;
begin
for yb in ybs(20) loop
dbms_output.put_line(yb.job||'.'||yb.sal);
end loop;
end;
/*
更新工資小案例 總裁1000 經理800 其他400 emp表
*/
declare
-- 創建遊戲包含emp所有用戶
cursor ybs is select * from emp;
yb emp%rowtype; -- 定義變量
begin
-- 打開遊標
open ybs;
-- 循環提出數據
loop
fetch ybs into yb;
exit when ybs%notfound;
-- 分條件進行更新數據 總裁1000 經理800 其他400 emp表
if yb.job='PRESIDENT' then
update emp set sal = sal + 1000 where empno = yb.empno;
elsif yb.job='MANAGER' then
update emp set sal = sal + 800 where empno = yb.empno;
else
update emp set sal = sal + 400 where empno = yb.empno;
end if;
end loop;
--關閉遊標
close ybs;
-- 提交事務
commit;
end;