find column names and table names referenced in SQL

前端 未结 3 1135
春和景丽
春和景丽 2021-01-07 03:32

How to find all the tables and column names used in a SQL? It is on ORACLE database. Below is an SQL example.

SELECT 
   A.ENAME,
   A.AGE as EMP_AGE,
   B         


        
3条回答
  •  无人及你
    2021-01-07 04:12

    I have a great solution for you, but there are two things you will need to do:

    1. Place the SQL inside a PL/SQL program unit. So, yes, to the stored procedure you mentioned.

    2. Compile that program unit and all dependent tables (that is, install your application code) on a 12.2 instance (you can download 12.2 at http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html or you can purchase an Exadata Express CLoud Service at cloud.oracle.com or get a $300 credit to use one at no cost for a month at cloud.oracle.com/tryit).

    12.2 is key because the feature you REALLY want to use is called PL/Scope and it is a compiler tool that collections information about PL/SQL identifiers (as of 11.1) and SQL usage inside PL/'SQL (as of 12.2).

    CREATE TABLE my_data (n NUMBER)
    /
    
    ALTER SESSION SET plscope_settings='identifiers:all, statements:all'
    /
    
    CREATE OR REPLACE PROCEDURE my_procedure (n_in IN NUMBER)
       AUTHID DEFINER
    IS
       l_n           my_data.n%TYPE;
    
       CURSOR all_data_cur
       IS
              SELECT *
                FROM my_data
          FOR UPDATE OF n;
    BEGIN
       INSERT INTO my_data (n)
            VALUES (n_in);
    
    END;
    /
    
      SELECT idt.line,
             idt.owner || '.' || idt.object_name code_unit, 
             idt.name column_name,
             RTRIM (src.text, CHR (10)) text
        FROM all_identifiers idt, all_source src
       WHERE     idt.usage = 'REFERENCE'
             AND idt.TYPE = 'COLUMN'
             AND idt.line = src.line
             AND idt.object_name = src.name
             AND idt.owner = src.owner
             AND idt.object_name = 'MY_PROCEDURE'
    ORDER BY code_unit, line
    /
    
    LINE CODE_UNIT          COLUMN_NAME TEXT  
    4   STEVEN.MY_PROCEDURE N           l_n           my_data.n%TYPE;
    10  STEVEN.MY_PROCEDURE N           FOR UPDATE OF n;
    12  STEVEN.MY_PROCEDURE N           INSERT INTO my_data (n)
    

    Hope that helps!

    Lots more examples of PL/Scope at livesql.oracle.com. Just search for "pl/scope" (duh).

提交回复
热议问题