sql – oracle 10g从单个select语句中获取所有选定的列和数据类型

我想从单个select语句中获取所有选定的列而不执行执行.查询可能使用join或union,那么查询可能不只是一个表,所以我不能简单地使用该语句

select column_name, data_type
from user_tab_cols
where table_name = 'my_table_name'

得到结果.

例如

输入:

select db1.*
  from (select dept_code,
               vital_signs,
               units,
               log_time
          from table1
         where dept_code = '111'
        union
        select 'hl06' as dept_code,
               vital_signs,
               units,
               log_time
          from table2
         where isdefault = 1
           and vital_signs not in
               (select vital_signs
                  from Ward_Vs_Vital_Signs
                 where dept_code = '111')) db1,
       table3 db2
 where db1.vital_signs = db2.vital_signs(+)
 order by db2.serial_no 

输出:

column_name  | data_type
-------------------------
dept_code    | VARCHAR 
vital_signs  | NUMBER
units        | VARCHAR
log_time     | DATE

我的问题是如何解析查询并要求数据库告诉我将在不执行语句的情况下返回的列和数据类型?谢谢 !

PS:我正在使用Oracle 10g.

最佳答案
使用单个select语句没有简单的方法,但是,您可以查看dbms_sql方法(DOC).

    14:32:26 SYSTEM@dwal> ed
Wrote file S:\spool\dwal\BUFFER_SYSTEM_329.sql

  1  DECLARE
  2    c           NUMBER;
  3    d           NUMBER;
  4    col_cnt     INTEGER;
  5    rec_tab     DBMS_SQL.DESC_TAB;
  6    col_num    NUMBER;
  7    PROCEDURE print_rec(rec in DBMS_SQL.DESC_REC) IS
  8    BEGIN
  9      DBMS_OUTPUT.NEW_LINE;
 10      DBMS_OUTPUT.PUT_LINE('col_name            =    ' || rec.col_name);
 11      DBMS_OUTPUT.PUT_LINE('col_type            =    ' || rec.col_type);
 12    END;
 13  BEGIN
 14    c := DBMS_SQL.OPEN_CURSOR;
 15    DBMS_SQL.PARSE(c, 'SELECT dummy, 12345 num, sysdate dt FROM dual', DBMS_SQL.NATIVE);
 16    d := DBMS_SQL.EXECUTE(c);
 17    DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
 18    col_num := rec_tab.first;
 19    IF (col_num IS NOT NULL) THEN
 20      for i in 1 .. col_cnt LOOP
 21        print_rec(rec_tab(i));
 22      END LOOP;
 23    END IF;
 24    DBMS_SQL.CLOSE_CURSOR(c);
 25* END;
14:32:46 SYSTEM@dwal> /
col_name            =    DUMMY
col_type            =    1
col_name            =    NUM
col_type            =    2
col_name            =    DT
col_type            =    12

PL/SQL procedure successfully completed.

注意上面的col_type数值 – 它是一个映射到实际数据类型的类型代码.映射记录在此处:http://docs.oracle.com/cd/E11882_01/server.112/e17118/sql_elements001.htm#i54330

转载注明原文:sql – oracle 10g从单个select语句中获取所有选定的列和数据类型 - 代码日志