I'm wondering if it's possible to dynamically evaluate a case-statement in the select
statement in Oracle SQL. Take the following pseudo sql code as an example:
WITH temp AS (
SELECT
'WHEN ' || when_col || ' THEN ''' || then_value || '''' as case_logic
FROM some_table
)
SELECT
case
{temp.case_logic} -- EVALUATE THIS FOR ALL ROWS IN TEMP DURING RUNTIME
else 'NA'
end as case_when,
table2.*
FROM table2;
I tried implementing the above with placeholders, as follows:
DECLARE
case_when_logic VARCHAR2(4000 byte);
plsql_block VARCHAR2(4000 byte);
TYPE case_when_logic_tbl_type IS TABLE OF VARCHAR2(1000 BYTE);
case_when_logic_tbl case_when_logic_tbl_type;
BEGIN
case_when_logic := q'[SELECT 'WHEN ' | | when_condition_col | | ' THEN ''' | | then_condition_col | | '''' as case_when FROM some_table]';
execute immediate case_when_logic BULK COLLECT INTO case_when_logic_tbl;
plsql_block := q'[SELECT CASE :case_when
ELSE 'some other value'
END case_when_col,
table2.*
FROM table2]';
EXECUTE IMMEDIATE plsql_block USING case_when_logic_tbl;
END;
/
But unfortunately this throws an error:
PLS-00457: expressions have to be of SQL types
Is there a way of accomplishing this? Please provide an example in code, as I have not seen analogous solutions.