sql >> Database >  >> RDS >> Oracle

Oracle krijgt tabelnamen op basis van kolomwaarde

Deze query kan in één stap worden gedaan met behulp van de (niet-verouderde) XMLTABLE.

Voorbeeldschema

--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;

Zoekopdracht

--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'
);

Resultaten

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


  1. Execute Immediate mislukt zelfs met CREATE table grant

  2. Shell-script om pgsql-commando's in bestanden uit te voeren

  3. Genereer DEFAULT-waarden in een CTE UPSERT met behulp van PostgreSQL 9.3

  4. Hoe e-mail verzenden vanuit SQL Server?