How to select a column from all tables in which it resides?

前端 未结 3 1726
北海茫月
北海茫月 2021-01-07 01:58

I have many tables that have the same column \'customer_number\'. I can get a list of all these table by query:

SELECT table_name FROM ALL_TAB_COLUMNS 
WHERE         


        
3条回答
  •  再見小時候
    2021-01-07 02:10

    DBMS_XMLGEN enables you to run dynamic SQL statements without custom PL/SQL.

    Sample Schema

    create table table1(customer_number number, a number, b number);
    insert into table1 values(1,1,1);
    create table table2(customer_number number, a number, c number);
    insert into table2 values(2,2,2);
    create table table3(a number, b number, c number);
    insert into table3 values(3,3,3);
    

    Query

    --Get CUSTOMER_NUMBER and A from all tables with the column CUSTOMER_NUMBER.
    --
    --Convert XML to columns.
    select
        table_name,
        to_number(extractvalue(xml, '/ROWSET/ROW/CUSTOMER_NUMBER')) customer_number,
        to_number(extractvalue(xml, '/ROWSET/ROW/A')) a
    from
    (
        --Get results as XML.
        select table_name,
            xmltype(dbms_xmlgen.getxml(
                'select customer_number, a from '||table_name
            )) xml
        from user_tab_columns
        where column_name = 'CUSTOMER_NUMBER'
    );
    
    
    TABLE_NAME  CUSTOMER_NUMBER  A
    ----------  ---------------  -
    TABLE1      1                1
    TABLE2      2                2
    

    Warnings

    These overly generic solutions often have issues. They won't perform as well as a plain old SQL statements and they are more likely to run into bugs. In general, these types of solutions should be avoided for production code. But they are still very useful for ad hoc queries.

    Also, this solution assumes that you want the same columns from each row. If each row is different then things get much more complicated and you may need to look into technologies like ANYDATASET.

提交回复
热议问题