sql >> Databasteknik >  >> RDS >> Oracle

Oracle får tabellnamn baserat på kolumnvärde

Den här frågan kan göras i ett steg med hjälp av (icke-utfasad) XMLTABLE.

Exempelschema

--Table-1 and Table-2 match the criteria.
--Table-3 has the right column but not the right value.
--Table-4 does not have the right column.
create table "Table-1" as select '1234' employee_id from dual;
create table "Table-2" as select '1234' employee_id from dual;
create table "Table-3" as select '4321' employee_id from dual;
create table "Table-4" as select 1          id from dual;

Fråga

--All tables with the column EMPLOYEE_ID, and the number of rows where EMPLOYEE_ID = '1234'.
select table_name, total
from
(
    --Get XML results of dynamic query on relevant tables and columns.
    select
        dbms_xmlgen.getXMLType(
            (
                --Create a SELECT statement on each table, UNION ALL'ed together.
                select listagg(
                    'select '''||table_name||''' table_name, count(*) total
                     from "'||table_name||'" where employee_id = ''1234'''
                    ,' union all'||chr(10)) within group (order by table_name) v_sql
                from user_tab_columns
                where column_name = 'EMPLOYEE_ID'
            )
        ) xml
    from dual
) x
cross join
--Convert the XML data to relational.
xmltable('/ROWSET/ROW'
    passing x.xml
    columns
        table_name varchar2(128) path 'TABLE_NAME',
        total      number        path 'TOTAL'
);

Resultat

TABLE_NAME   TOTAL
----------   -----
Table-1      1
Table-2      1
Table-3      0


  1. Få totalt arbetade timmar på en dag mysql

  2. Installera Oracle 12c Standard Edition på Windows 10 Professional

  3. Laravel tidsstämplar för att visa millisekunder

  4. Förberedd sats kan inte köras flera gånger med heltalsvärden