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

Kueri tabel dan nama kolom yang disimpan dalam tabel

Menggunakan kueri Peter M untuk membuat teks SQL, dan kemudian memanfaatkan kekuatan gelap 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;

Pertanyaan:

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;

Hasil:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. ROWDTOCHAR() Fungsi di Oracle

  2. TEMPFILE Offline Fisik Siaga

  3. Kesalahan saat mencoba mengganti nama kolom dengan spasi di tabel Oracle. Kesalahan - Kesalahan SQL:ORA- 00946:hilang TO kata kunci

  4. C# - Haruskah saya menggunakan koneksi database statis?

  5. skrip shell untuk menemukan nama file &jumlah baris setiap file, sekarang masukkan catatan ini ke tabel Oracle