當在PL/SQL塊中執行DML和單行SELECT INTO 語句時,Oracle會分配隱含遊標。爲了處理SELECT語句返回的多行數據,需要使用顯式遊標
何謂SELECT INTO
SELECT INTO 語句從一個表中選取數據,然後把數據插入另一個表中。
SELECT INTO 語句常用於創建表的備份復件或者用於對記錄進行存檔。
語法
1、把所有的列插入新表:
SELECT *INTO new_table_name [IN externaldatabase] FROM old_tablename
2、只把希望的列插入新表:
SELECT column_name(s)INTO new_table_name [IN externaldatabase] FROM old_tablename
顯式遊標專門用於處理SELECT語句返回的多行數據,其包含四個屬性——%ISOPEN,%FOUNT,%NOTFOUNT,%ROWCOUNT
當使用顯式遊標時,必須經歷定義遊標,打開遊標,提取數據,關閉遊標四個階段
1) 標量變量接收遊標數據
CURSOR student_cursor IS——定義遊標
SELECT id,name FROM student WHERE id = &number;
v_namestudent.name%TYPE;
v_idstudent.id%TYPE;
BEGIN
OPEN student_cursor;——打開遊標
LOOP
FETCH student_cursor INTO v_id,v_name;——提取數據
//這裏不可寫v_name,v_id,必須和CURSOR中定義的SELECT的順序一致
EXIT WHEN student_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(‘學號:’ || v_id || ‘姓名:’ || v_name);
END LOOP;
CLOSE student_cursor;——關閉遊標
END;
2) 記錄變量接受遊標數據
DECLARE
CURSOR student_cursor_define IS
SELECT name,idFROM student WHERE id > 1;
student_cursorstudent_cursor_define%ROWTYPE;
BEGIN
OPENstudent_cursor_define;
LOOP
FETCHstudent_cursor_define INTO student_cursor;
EXITWHENstudent_cursor_define%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(‘學號:’ || student_cursor.id || ‘姓名:’ ||student_cursorname);
ENDLOOP;
CLOSEstudent_cursor_define;
END;
3) 更新遊標行
DECLARE
CURSOR student_cursor IS
SELECT name,id FROM studentFOR UPDATE;
BEGIN
FOR num IN student_cursor LOOP
IF num.id = 25 THEN
DBMS_OUTPUT.PUT_LINE('姓名:' || num.name || '原學號:' || num.id);
UPDATE student SET id = 5231600 +id WHERE CURRENT OF student_cursor;
END IF;
END LOOP;
CLOSE student_cursor;
END;
4) 批量提取
Oracle 9i後可以使用FETCH…BULK COLLECT提取所有數據
DECLARE
CURSOR student_cursor IS
SELECT * FROM student WHERE id = 5231625;
TYPE student_TABLE_TYPE IS TABLE OF student%ROWTYPE;
student_tablestudent_TABLE_TYPE;
BEGIN
OPEN student_cursor;
FETCH student_cursor BULK COLLECT INTO student_table;
CLOSE student_cursor;
FOR i IN 1..student_table.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('學號:' ||student_table(i).id || '姓名:' ||student_table(i).name);
END LOOP;