Oracle - get table name from sql text

后端 未结 1 1281
孤街浪徒
孤街浪徒 2021-01-14 13:39

I have a column in a table with simple sql queries and I want to regexp_substr the table name from them. Examples of texts:

SELECT PT.PT_PARTY_NAME VALUE,PT.         


        
相关标签:
1条回答
  • 2021-01-14 14:07

    Rather than try to write your own parser, you could let Oracle parse it for you via explain plan, and then look at the plan table to see which objects it refers to:

    declare
      text varchar2(4000) := 'SELECT PT.PT_PARTY_NAME VALUE,PT.PT_PARTY_NAME LABEL
        FROM DWH_OWNER.DWH_ACCOUNTS ACC,
             DWH_OWNER.DWH_PARTIES PT
       WHERE ACC.ACC_SOURCE_ID = :P_DOMVAL_REF1
        AND ACC.ACC_PT_KEY = PT.PT_KEY';
    begin
      execute immediate 'explain plan for ' || text;
    end;
    /
    
    select distinct object_owner, object_name
    from plan_table
    where object_type = 'TABLE';
    
    OBJECT_OWNER                   OBJECT_NAME                  
    ------------------------------ ------------------------------
    DWH_OWNER                      DWH_ACCOUNTS                  
    DWH_OWNER                      DWH_PARTIES                   
    

    As @Aleksej suggested, if the optimiser only uses an index (so the execution plan shows index access/scan without hitting the table, because all the relevant columns are in the index) then the plan table only reports the index. You could allow for that by joining to the index view; if it hits the table too it'll just report it for both:

    select distinct case when pt.object_type = 'INDEX' then ai.table_owner
        else pt.object_owner end as owner,
      case when pt.object_type = 'INDEX' then ai.table_name
        else pt.object_name end as table_name
    from plan_table pt
    left join all_indexes ai on ai.owner = pt.object_owner
    and ai.index_name = pt.object_name
    where pt.object_type in ('TABLE', 'INDEX');
    

    You also need to make sure the plan table is empty before each explain plan call and query to avoid confusion, or set a statement ID so you can identify which tables related to the current query.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题