Oracle 遊標的各種寫法
阿新 • • 發佈:2018-11-08
-- for .. in `隱式遊標` BEGIN FOR RS IN (SELECT column_1 FROM table_name) LOOP dbms_output.put_line(RS.column_1); END LOOP; END; -- RS 必須是單個欄位 DECLARE CURSOR RS IS SELECT column_1 FROM table_name; column_1 VARCHAR2(50); BEGIN OPEN RS; LOOP FETCH RS INTO column_1; EXIT WHEN RS%NOTFOUND; dbms_output.put_line(column_1); END LOOP; CLOSE RS; END; / -- bulk collect顯示遊標 DECLARE CURSOR RS IS SELECT column_1 FROM table_name; column_1_array dbms_sql.Varchar2_Table; BEGIN OPEN RS; FETCH RS BULK COLLECT INTO column_1_array; FOR i IN 1 .. column_1_array.count LOOP dbms_output.put_line(column_1_array(i)); END LOOP; CLOSE RS; END; -- bulk collect 顯示遊標 + limit DECLARE CURSOR RS IS SELECT column_1 FROM table_name; column_1_array dbms_sql.Varchar2_Table; BEGIN OPEN RS; LOOP FETCH RS BULK COLLECT INTO column_1_array LIMIT 2; EXIT WHEN RS%NOTFOUND; FOR i IN 1 .. column_1_array.count LOOP dbms_output.put_line(column_1_array(i)); END LOOP; END LOOP; CLOSE RS; END; - select into 隱式遊標 DECLARE column_1 VARCHAR2(100); BEGIN SELECT zone_code INTO column_1 FROM table_name WHERE ROWNUM = 1; dbms_output.put_line(column_1); END; - 動態sql,select into 隱式遊標 DECLARE column_1 VARCHAR2(50); l_table VARCHAR2(200); l_sql VARCHAR2(200); BEGIN l_table := 'table_name'; l_sql := 'select column_1 from ' || l_table || ' where rownum = 1'; EXECUTE IMMEDIATE l_sql INTO column_1; dbms_output.put_line(column_1); END; - 動態sql select into 隱式遊標 + bulk collect DECLARE column_1_array dbms_sql.Varchar2_Table; l_table VARCHAR2(20); l_sql VARCHAR2(100); BEGIN l_table := 'table_name'; l_sql := 'select column_1 from ' || l_table; EXECUTE IMMEDIATE l_sql BULK COLLECT INTO column_1_array; FOR i IN 1 .. column_1_array .count LOOP dbms_output.put_line(column_1_array(i)); END LOOP; END;