Oracle資料庫中遊標的使用

來源:互聯網
上載者:User

遊標的定義:

    • ---遊標的使用declare  --定義一個遊標,將tab_stu所有資料提取出來 cursor c_tab_stu is select * from tab_stu;  r_tab_stu tab_stu%rowtype;--使用rowtype儲存遊標資料 begin  --開啟遊標  open c_tab_stu;  --提取資料  fetch c_tab_stu into r_tab_stu;  dbms_output.put_line('stu_id:'||r_tab_stu.stu_id);  dbms_output.put_line('stu_name:'||r_tab_stu.stu_name);  dbms_output.put_line('stu_age:'||r_tab_stu.stu_age);  --關閉遊標  close c_tab_stu;end;

    • --使用迴圈提取所有記錄declare  --定義一個遊標,將tab_stu所有資料提取出來 cursor c_tab_stu is select * from tab_stu;  r_tab_stu tab_stu%rowtype;--使用rowtype儲存遊標資料 begin  --開啟遊標  open c_tab_stu;  --提取資料  loop      fetch c_tab_stu into r_tab_stu;     --允出準則,也就是上面圖片的屬性的值     exit when c_tab_stu%notfound;          dbms_output.put_line('stu_id:'||r_tab_stu.stu_id);     dbms_output.put_line('stu_name:'||r_tab_stu.stu_name);     dbms_output.put_line('stu_age:'||r_tab_stu.stu_age);       end loop;   --關閉遊標  close c_tab_stu;end;

    • --含有條件的遊標--實現目標是,查詢每個班的學生declare--先要定義兩個遊標--定義tab_class遊標cursor s_tab_class isselect * from tab_class;--定義tab_stu遊標,但是這裡需要一個參數,就是班級的idcursor s_tab_stu(v_class_id number) isselect * from tab_stu where class_id=v_class_id;--定義兩個儲存變數--定義tab_classv_tab_class_rowtype tab_class%rowtype;--定義tab_stuv_tab_stu_rowtype tab_stu%rowtype;begin  --開啟遊標  open s_tab_class;  loop    --提取資料    fetch s_tab_class into v_tab_class_rowtype;    exit when s_tab_class%notfound;    dbms_output.put_line('班級:'||v_tab_class_rowtype.class_name||'含有');    --嵌套迴圈,遍曆當前班級的學生    open s_tab_stu(v_tab_class_rowtype.class_id);    loop      fetch s_tab_stu into v_tab_stu_rowtype;      exit when s_tab_stu%notfound;      dbms_output.put_line(v_tab_stu_rowtype.stu_name);    end loop;    close s_tab_stu;  end loop;  close s_tab_class;end;

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.