I am facing an issue with a function that I'm working on. The function aims to retrieve a column value based on the input parameters and a requested column name of that table. However, when I try to compile its code, which is the following:
CREATE OR REPLACE FUNCTION FIND_TEST_TABLE_COLUMN(
IN_COLUMN1 TEST_TABLE.COLUMN1 % TYPE,
IN_COLUMN2 TEST_TABLE.COLUMN2 % TYPE,
IN_COLUMN3 TEST_TABLE.COLUMN3 % TYPE,
IN_COLUMN4 TEST_TABLE.COLUMN4 % TYPE,
IN_REQUESTED_COLUMN VARCHAR2
) RETURN VARCHAR2 IS
C_TEST_TABLE SYS_REFCURSOR;
RESULT VARCHAR2(255);
BEGIN
IF IN_COLUMN4 IS NULL THEN
OPEN C_TEST_TABLE FOR
SELECT *
FROM TEST_TABLE
WHERE COLUMN1 = COLUMN1
AND COLUMN2 = IN_COLUMN2
AND COLUMN3 = IN_COLUMN3;
ELSIF IN_COLUMN4 IS NOT NULL THEN
OPEN C_TEST_TABLE FOR
SELECT *
FROM TEST_TABLE
WHERE COLUMN1 = COLUMN1
AND COLUMN2 = IN_COLUMN2
AND COLUMN3 = IN_COLUMN3
AND COLUMN4 = IN_COLUMN4;
END IF;
FOR C_TEST_TABLE_REC IN C_TEST_TABLE
LOOP
IF IN_REQUESTED_COLUMN = 'COLUMN1' THEN
RESULT := C_TEST_TABLE_REC.COLUMN1;
EXIT;
ELSIF IN_REQUESTED_COLUMN = 'COLUMN2' THEN
RESULT := C_TEST_TABLE_REC.COLUMN2;
EXIT;
ELSIF IN_REQUESTED_COLUMN = 'COLUMN3' THEN
RESULT := C_TEST_TABLE_REC.COLUMN3;
EXIT;
END IF;
END LOOP;
RETURN RESULT;
END;
I receive the following error:
[Warning] ORA-24344: success with compilation error 19/27 PLS-00221: 'C_TEST_TABLE' is not a procedure or is undefined 19/5 PL/SQL: Statement ignored (1: 0): Warning: compiled but with compilation errors
that indicates that C_TEST_TABLE cannot be used after the declaration block
You don't need to use cursors:
Which, for the sample data:
Then:
Outputs:
If you want to fix your code then you need to declare the variable
C_TEST_TABLE_RECand useFETCH(and can remove the loop and simplify the code to):fiddle