sql >> Database teknologi >  >> RDS >> Oracle

Forespørg en tabel og et kolonnenavn gemt i en tabel

Brug af Peter M's forespørgsel til at bygge SQL-teksten og derefter udnytte den mørke kraft i XML:

create table attributes (id, entity_id, table_name, column_name)
as
select 1, 3, 'VALUES_A', 'VALUE_1' from dual union all
select 2, 2, 'VALUES_B', 'VALUE_3' from dual union all
select 3, 2, 'VALUES_A', 'VALUE_2' from dual;

create table values_a (entity_id, value_1, value_2, value_3)
as
select 1, 'Monday', 42, 'Green' from dual union all
select 2, 'Sunday', 3000, 'Blue' from dual union all
select 3, 'Wednesday', 1, 'Black' from dual;

create table values_b (entity_id, value_1, value_2, value_3)
as
select 1, 'Tuesday', 26, 'Green' from dual union all
select 2, 'Saturday', 3, 'Red' from dual union all
select 3, 'Wednesday', 15, 'White' from dual;

Forespørgsel:

with queries as
     ( select table_name, column_name, entity_id
            , 'select '|| column_name || ' as c from ' || table_name ||
             ' where entity_id = ' || entity_id ||
              case
                  when id = max_id then ''
                  else ' union all '
              end as sqltext
       from 
           ( select a.*, max(a.id) over (order by id) max_id from attributes a ) )
select table_name, column_name, entity_id
     , extractvalue(xmltype(dbms_xmlgen.getxml(sqltext)),'/ROWSET/ROW/C') as sql_result
from   queries;

Resultater:

TABLE_NAME COLUMN_NAME  ENTITY_ID SQL_RESULT
---------- ----------- ---------- ---------------------------------------------------
VALUES_A   VALUE_1              3 Wednesday
VALUES_B   VALUE_3              2 Red
VALUES_A   VALUE_2              2 3000


  1. hvad er og hvordan fjerner jeg tablespace-fejl fra min database?

  2. Sådan indstilles maxrecursion-indstillingen for en CTE inde i en Tabel-Valued-Function

  3. Hvordan opretter jeg en indlejret funktion i PL/pgSQL?

  4. At lave livesøgning på en database med CodeIgniter, php5 og MySQL