我有一個pl \ sql過程,需要使用dbms_sql包在curosr循環中查看記錄。使用光標記錄作爲數組
遊標查詢是動態的,所以你不知道列。
所以每次我想使用dbms_sql.define_columns或其他函數時,我都是通過all_tab_columns上的循環來獲取列名。
這是我的代碼:
procedure p is
SOURCE_CURSOR INTEGER;
destination_cursor INTEGER;
IGNORE INTEGER;
destination_cursor INTEGER;
v_stmt clob := empty_clob();
V_COLS_LIST varchar2(4000);
V_COLS_LIST2 varchar2(4000);
V_UPDATE_DATE_COL_NAME varchar2(30) := 'UPDATE_DATE_COL';
begin
-- going over all the records. each record is a table
for CURR_TABLE in (select * from mng_tables)
loop
-- get the column list for the current table
SELECT LISTAGG(CLS.COLUMN_NAME, ',') WITHIN GROUP (ORDER BY COLUMN_ID)
INTO V_COLS_LIST
FROM ALL_TAB_COLUMNS CLS
WHERE CLS.TABLE_NAME = CURR_TABLE.HISTORY_TABLE_NAME
AND CLS.OWNER = CURR_TABLE.HISTORY_TABLE_OWNER
AND CLS.COLUMN_NAME <> V_UPDATE_DATE_COL_NAME;
-- prepare the select from current table
v_stmt := 'select ' || V_COLS_LIST || ', SYSDATE' ||
' from ' || CURR_TABLE.TABLE_OWNER || '.' || CURR_TABLE.TABLE_NAME;
-- prepare the dynamic sql
-- get cursor id
source_cursor := dbms_sql.open_cursor;
-- parse cursor with query
DBMS_SQL.PARSE(SOURCE_CURSOR,V_STMT, DBMS_SQL.NATIVE);
-- going over all the columns of current table and define matching columns
FOR rec in (SELECT *
FROM ALL_TAB_COLUMNS
WHERE CLS.TABLE_NAME = CURR_TABLE.HISTORY_TABLE_NAME
AND CLS.OWNER = CURR_TABLE.HISTORY_TABLE_OWNER)
loop
DBMS_SQL.DEFINE_COLUMN(source_cursor, rec.column_id, rec.data_type);
end loop;
-- execute the select query
IGNORE := DBMS_SQL.EXECUTE(SOURCE_CURSOR);
-- define the destination cursor
destination_cursor := DBMS_SQL.OPEN_CURSOR;
select replace(V_COLS_LIST, ',' , ':,')
into V_COLS_LIST2
from dual;
-- parse the
DBMS_SQL.PARSE(destination_cursor,
'insert /*+ parallel(8) */ into ' || CURR_TABLE.HISTORY_TABLE_OWNER || '.' || CURR_TABLE.HISTORY_TABLE_NAME ||
'(' || V_COLS_LIST || ',' || V_UPDATE_DATE_COL_NAME || ')' ||
' values (:' || V_COLS_LIST2 || ',sysdate)',
DBMS_SQL.NATIVE);
LOOP
-- if there is a row
IF DBMS_SQL.FETCH_ROWS(source_cursor)>0 THEN
FOR rec in (SELECT *
FROM ALL_TAB_COLUMNS
WHERE CLS.TABLE_NAME = CURR_TABLE.HISTORY_TABLE_NAME
AND CLS.OWNER = CURR_TABLE.HISTORY_TABLE_OWNER)
loop
-- get column values of the row
DBMS_SQL.COLUMN_VALUE(source_cursor, rec.column_id, ???);
DBMS_SQL.BIND_VARIABLE(destination_cursor, ':' || rec.column_name, ???);
end loop;
ignore := DBMS_SQL.EXECUTE(destination_cursor);
ELSE
-- No more rows to copy:
EXIT;
END IF;
end loop;
end loop;
end p;
但是當我要綁定變量,我不能這樣做,監守我不能有動態值..
到底當我這樣做的程序:
DBMS_SQL.COLUMN_VALUE(source_cursor, rec.column_id, ???);
DBMS_SQL.BIND_VARIABLE(destination_cursor, ':' || rec.column_name, ???);
我只是想更換???像「my_rec [rec.column_name]」 或「my_rec [rec.column_id]」,並獲取該列中記錄的值。
有什麼想法?
謝謝。
我有我的理由不使用inser-select,即使它實際上是微不足道的方法。我修正了發佈的問題,這就是當你不把我原來的代碼時會發生什麼。你的代碼幫助了我!非常感謝! – user2671057