sql >> Databáze >  >> RDS >> Oracle

Oracle získá názvy tabulek na základě hodnoty sloupce

Tento dotaz lze provést v jednom kroku pomocí (nezastaralé) XMLTABLE.

Ukázkové schéma

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

Dotaz

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

Výsledky

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


  1. jak implementovat Northwind v Django

  2. SQL - výkon ve varchar vs. int

  3. Jak mohu UPDATE z SELECT v SQL Server?

  4. Použití proměnné v dotazu OPENROWSET