Oracle
 sql >> Teknologi Basis Data >  >> RDS >> Oracle

Oracle mendapatkan nama tabel berdasarkan nilai kolom

Kueri ini dapat dilakukan dalam satu langkah menggunakan XMLTABLE (tidak digunakan lagi).

Contoh Skema

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

Kueri

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

Hasil

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


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Oracle ORA-00933:Perintah SQL tidak berakhir dengan benar?

  2. SQL dengan peringkat dan partisi

  3. Instal Driver Attunity Oracle di Visual Studio 2017

  4. PLSQL JDBC:Bagaimana cara mendapatkan ID baris terakhir?

  5. SQL Server Setara dengan Bulk Collect di Oracle