1. 程式人生 > >oracle遊標一 靜態遊標-顯示遊標-宣告&初始化

oracle遊標一 靜態遊標-顯示遊標-宣告&初始化

oracle靜態遊標-顯示遊標的使用

目錄:

1. 遊標語法

2. 遊標的使用

2.1 宣告遊標並初始化

2.2 宣告多個變數接收遊標返回值

2.3 宣告一個record變數接收遊標返回值

2.4 開啟/關閉遊標

2.5 獲取遊標中的值

2.6 重複使用遊標(需要先close, 才能二次open)

 

1. 遊標語法

cursor 遊標名稱 [引數1, 引數2] is 遊標資料來源
引數可有,可無
eg:
    --有引數
    cursor stu_cusor(v_scort number := 70) is select * from t_student t where t.scort >= v_scort ;
    --沒有引數
     cursor stu_cusor is select * from t_student t where t.scort >= 80 ;

2. 遊標的使用

create or replace procedure pro_student as
    --方式一:分別宣告變數, 用來接收遊標中的值
    v_stu_name varchar2(20);--自定義變數型別
    v_stu_bir t_student.birthday%type;--變數型別和t_student表中的birthday欄位型別一致。
    --方式二:集中宣告變數, 用來接收遊標中的值
    -- 定義record型別
    type record_student is record (
        stu_name varchar2(20),
        stu_bir date
    );
    --宣告record型別的的變數
    rec_stu record_student;

    -- 1. 宣告遊標,及其值得獲取方式
    cursor cursor_student(v_score number := 70) is select t.name, t.birthday from t_student t where t.score >= v_score;
    begin 
        --2.開啟遊標
        if not cursor_student%isopen then
            open cursor_student(80);--獲取分數大於80的資料列表
        end if;
        --3. 迴圈獲取遊標中的值
        loop
            --獲取遊標中的值, 並賦值給變數
            fetch cursor_student into v_stu_name, v_stu_bir;
            -- 遊標中沒有值得時候,退出loop
            exit when cursor_student%notfound;
            dbms_output.put_line('namex='||v_stu_name ||', birthday='||v_stu_bir);
        end loop;
        --4.關閉遊標
        close cursor_student;
        
        --5. 獲取這個遊標其他條件值的資料列表。 二次使用前, 需要先關閉這個遊標
        open cursor_student(85);--獲取分數大於90的資料列表
        loop
             fetch cursor_student into rec_stu;
             exit when cursor_student%notfound;
             dbms_output.put_line('namey='||rec_stu.stu_name ||', birthday='||rec_stu.stu_bir);
        end loop;
        close cursor_student;
    end pro_student ;