PL/SQL基礎篇5(遊標)

 -- 接着上篇的內容

-- 顯示遊標4:用遊標更新數據,關鍵字:select ... for update

select * from emp;

declare

  v_sal number;

  cursor emp_cur is select * from emp where sal<1500 for update of sal; -- 更新sal字段

begin

  for c in emp_cur

    loop

      v_sal := c.sal;

      update emp set sal = v_sal*1.2 where current of emp_cur;-- 當前遊標所指的行

    end loop;

end;

--  REF遊標:用於處理運行時動態地執行sql查詢

declare

   type emp_ref is ref cursor; --聲明一個遊標類型,此處又有不同哦

   emp_cur emp_ref;-- 聲明一個遊標,類型是上面定義好的類型

   v_emp emp%rowtype;

   v_sal number := '&輸入薪水:';

begin

   open emp_cur for 'select * from emp where sal>:s' --此處可以是字符串,也就是可以動態傳值的

   using v_sal; --給佔位符綁值

   loop

     fetch emp_cur into v_emp;

     exit when emp_cur%notfound;

     sopV(v_emp.ename);

   end loop;

   close emp_cur;

end;

/*

    給遊標簡單的做個小結

    1.遊標用於處理查詢結果集中的數據

    2.遊標類型有:隱式遊標、顯式遊標和 REF 遊標                         

    3.隱式遊標由 PL/SQL 自動定義、打開和關閉

    4.顯式遊標用於處理返回多行的查詢

    5.顯式遊標可以刪除和更新活動集中的行

    6.要處理結果集中所有記錄時,可使用循環遊標

    7.在聲明 REF 遊標時,不需要將 SELECT 語句與 其關聯

*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章