简体   繁体   中英

Using column values from one table within a WHERE clause

I have an Oracle table called: col_mapping where a column in this table has the column values of columns from another table.

Example data of table: col_mapping

    ID    DESCR     COL_VALS
------------------------------
    1     LABEL     COL_1
    2     NAME_ADDR COL_2:COL_3
    3     SALARY    COL4

Based on the above table, I now would like to go through each record in col_mapping and use the COL_VALS as part of my WHERE condition in another table called other_tab , ie:

select 'Y' 
from other_tab
where COL_1 = 'whatever1';

select 'Y' 
from other_tab
where (COL_2 = 'whatever2' or COL_3 = 'whatever2');

and finally:

select 'Y' 
from other_tab
where COL_4 = 'whatever4';

I basically would like to split out COL_VALS into a where condition and where there is more than one value colon separated, turn it into an OR condition as above examples.

This is not tested. But this how I believe it can be accomplished. You need two loops. One to loop through the table col_mapping and the other to loop through the column COL_VALS for each row and construct the where condition.

Something like this:

DECLARE 

a_where_vars APEX_APPLICATION_GLOBAL.VC_ARR2;  --you can replace it with your own associative array here
l_where_string VARCHAR2(4000);

BEGIN

  For i IN (SELECT id, descr, col_vals FROM col_mapping)
  LOOP
  a_where_vars := APEX_UTIL.STRING_TO_TABLE(i.col_vals, ':')  --split values into array

    FOR j IN 1 .. a_where_vars.COUNT LOOP
    l_where_string := l_where_string||a_where_vars(j)||' = '||whatever_variable||' OR ';
    END LOOP;

  --you can remove last OR and clean up l_where_string 
  --then you query:
  EXECUTE IMMEDIATE := '
  select ''Y''
  from other_tab
  where '||l_where_string 
  END LOOP INTO some_binding_variables;
  --other queries.
END;
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM