Search code examples
oracle11gsqlplusdata-dictionary

Oracle: Script similar to describe command


I'm being asked to create a script that basically does the same thing as the describe command. I have figured out how to write the script and get the output I want, but the second part of the assignment is to "duplicate the format of the describe command" I'm stumped, is there really a way to simply duplicate that format?


Solution

  • Assuming your query is something like (note that I'm not bothering to handle every different data type)

    select column_name "Name",
           (case when nullable = 'N'
                 then 'NOT NULL'
                 else null
             end) "Null?",
           (case when data_type = 'DATE'
                 then data_type
                 when data_type = 'NUMBER' and data_scale > 0
                 then data_type || '(' || data_precision || ',' || data_scale || ')'
                 when data_type = 'NUMBER' and data_scale = 0
                 then data_type || '(' || data_precision || ')'
                 when data_type = 'VARCHAR2'
                 then data_type || '(' || data_length || ')'
            end) "Type"
      from dba_tab_cols
     where table_name = 'EMP'
     order by column_id
    

    You can issue some SQL*Plus commands to format the output

    SQL> column "Nmae" format a30;
    SQL> column "Null?" format a8;
    SQL> column "Type" format a30;
    

    and then the output of your query will match up with the output of the DESCRIBE command

    SQL> ed
    Wrote file afiedt.buf
    
      1  select column_name "Name",
      2         (case when nullable = 'N'
      3               then 'NOT NULL'
      4               else null
      5           end) "Null?",
      6         (case when data_type = 'DATE'
      7               then data_type
      8               when data_type = 'NUMBER' and data_scale > 0
      9               then data_type || '(' || data_precision || ',' || data_scale || ')'
     10               when data_type = 'NUMBER' and data_scale = 0
     11               then data_type || '(' || data_precision || ')'
     12               when data_type = 'VARCHAR2'
     13               then data_type || '(' || data_length || ')'
     14          end) "Type"
     15    from dba_tab_cols
     16   where table_name = 'EMP'
     17*  order by column_id
    SQL> /
    
    Name                           Null?    Type
    ------------------------------ -------- ------------------------------
    EMPNO                          NOT NULL NUMBER(4)
    ENAME                                   VARCHAR2(10)
    JOB                                     VARCHAR2(9)
    MGR                                     NUMBER(4)
    HIREDATE                                DATE
    SAL                                     NUMBER(7,2)
    COMM                                    NUMBER(7,2)
    DEPTNO                                  NUMBER(2)
    
    8 rows selected.