Oracle:向 refcursor 添加新行
Oracle: Add a new row to a refcursor
我有一个程序,returns refcursor 作为 OUT 参数。
我需要将它包装在一个新过程中并添加依赖于 refcursors 字段之一的新行。
由于所有游标都是 immutable 我被这个问题困住了。也许创建临时 table?
DECLARE
initial_cursor SYS_REFCURSOR;
result_cursor SYS_REFCURSOR;
BEGIN
initial_procedure(initial_cursor);
-- add a new row which depends on initial cursors row and wrap it into result cursor.
END;
让我们考虑初始游标将仅包含布尔值,新行将是 varchar 'TRUE' 或 'FALSE'(如果游标值为 0,则 'FALSE',否则 'TRUE')
您可以创建一个 PIPELINED
函数来读取游标并输出带有额外行的行:
CREATE FUNCTION add_row(
i_cur IN SYS_REFCURSOR,
i_value IN NUMBER
) RETURN SYS.ODCIVARCHAR2LIST PIPELINED
IS
v_value NUMBER;
v_flag BOOLEAN := TRUE;
BEGIN
LOOP
FETCH i_cur INTO v_value;
EXIT WHEN i_cur%NOTFOUND;
PIPE ROW (v_value);
IF v_value = 0 THEN
v_flag := FALSE;
END IF;
END LOOP;
IF v_flag THEN
PIPE ROW ('TRUE');
ELSE
PIPE ROW ('FALSE');
END IF;
END;
/
然后你可以用它来制作第二个光标:
DECLARE
initial_cursor SYS_REFCURSOR;
result_cursor SYS_REFCURSOR;
v_value VARCHAR2(20);
PROCEDURE initial_procedure(
cur OUT SYS_REFCURSOR
)
IS
BEGIN
OPEN cur FOR
SELECT 1 AS value FROM DUAL;
END;
BEGIN
initial_procedure(initial_cursor);
-- add a new row which depends on initial cursors row and wrap it into result cursor.
OPEN result_cursor FOR
SELECT COLUMN_VALUE AS value
FROM TABLE(add_row(initial_cursor, 2));
LOOP
FETCH result_cursor INTO v_value;
EXIT WHEN result_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_value);
END LOOP;
END;
/
输出:
1
TRUE
db<>fiddle here
我有一个程序,returns refcursor 作为 OUT 参数。
我需要将它包装在一个新过程中并添加依赖于 refcursors 字段之一的新行。 由于所有游标都是 immutable 我被这个问题困住了。也许创建临时 table?
DECLARE
initial_cursor SYS_REFCURSOR;
result_cursor SYS_REFCURSOR;
BEGIN
initial_procedure(initial_cursor);
-- add a new row which depends on initial cursors row and wrap it into result cursor.
END;
让我们考虑初始游标将仅包含布尔值,新行将是 varchar 'TRUE' 或 'FALSE'(如果游标值为 0,则 'FALSE',否则 'TRUE')
您可以创建一个 PIPELINED
函数来读取游标并输出带有额外行的行:
CREATE FUNCTION add_row(
i_cur IN SYS_REFCURSOR,
i_value IN NUMBER
) RETURN SYS.ODCIVARCHAR2LIST PIPELINED
IS
v_value NUMBER;
v_flag BOOLEAN := TRUE;
BEGIN
LOOP
FETCH i_cur INTO v_value;
EXIT WHEN i_cur%NOTFOUND;
PIPE ROW (v_value);
IF v_value = 0 THEN
v_flag := FALSE;
END IF;
END LOOP;
IF v_flag THEN
PIPE ROW ('TRUE');
ELSE
PIPE ROW ('FALSE');
END IF;
END;
/
然后你可以用它来制作第二个光标:
DECLARE
initial_cursor SYS_REFCURSOR;
result_cursor SYS_REFCURSOR;
v_value VARCHAR2(20);
PROCEDURE initial_procedure(
cur OUT SYS_REFCURSOR
)
IS
BEGIN
OPEN cur FOR
SELECT 1 AS value FROM DUAL;
END;
BEGIN
initial_procedure(initial_cursor);
-- add a new row which depends on initial cursors row and wrap it into result cursor.
OPEN result_cursor FOR
SELECT COLUMN_VALUE AS value
FROM TABLE(add_row(initial_cursor, 2));
LOOP
FETCH result_cursor INTO v_value;
EXIT WHEN result_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_value);
END LOOP;
END;
/
输出:
1 TRUE
db<>fiddle here