从查询中获取列名(不是从表中获取)

时间:2019-04-06 07:35:29

标签: oracle

是否有任何类似于Java ResultSetMetaData的方法来从查询中获取列名?请注意,当我遇到类似的查询

时,查询User_Tab_Columns不能为我提供帮助
Select 'Bruce' as "First_Name", 'Thomas' as "Middle_Name", 'Wayne' as "Last_Name"
From Dual

1 个答案:

答案 0 :(得分:2)

是的,您可以使用dbms_sql.describe_columns。此答案使用了从here

借来的代码的摘录

如果愿意,可以将其转换为TABLE函数,该函数返回任何给定查询的列名,以简化您的工作。我会把它留给您练习!

declare
    p_query varchar2(32767) := 
              q'{
                  Select 'Bruce'   as "First_Name", 'Thomas' 
                      as "Middle_Name", 'Wayne' as "Last_Name"
                   From Dual
                 }';
    l_theCursor     integer default dbms_sql.open_cursor;
    l_descTbl       dbms_sql.desc_tab;
    l_colCnt        number;

begin

    dbms_sql.parse(  l_theCursor,  p_query, dbms_sql.native );
    dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );

        for i in 1 .. l_colCnt loop
            dbms_output.put_line(  l_descTbl(i).col_name );
        end loop;

end;
/

输出

First_Name
Middle_Name
Last_Name


PL/SQL procedure successfully completed.

DEMO