简体   繁体   English

Pl / SQL-从查询中获取列名

[英]Pl/SQL- Get column names from a query

I'm using Pl/SQL with Oracle Database 11g. 我正在使用Pl / SQL和Oracle Database 11g。

I'm writing a function that takes in a select statement as a parameter (varchar2). 我正在编写一个函数,它将select语句作为参数(varchar2)。 The function uses a for loop to go over the rows and apply formatting to specific columns, and output the whole thing. 该函数使用for循环遍历行并将格式应用于特定列,并输出整个事物。 Basically, I need some way to get the column names so that I can display them at the top. 基本上,我需要一些方法来获取列名称,以便我可以在顶部显示它们。 I know there are various ways to do this for tables, but since this query is passed in, all columns may not have been selected, aliases may have been used, etc. 我知道有多种方法可以为表执行此操作,但由于传入此查询,因此可能未选择所有列,可能已使用别名等。

Is there a way I can select out the column names from this query? 有没有办法从这个查询中选择列名?
Ideally something like: 理想情况如下:
select column_names from (subquery)

I believe you can use DESCRIBE_COLUMNS to do this. 我相信你可以使用DESCRIBE_COLUMNS来做到这一点。 Just pass in the cursor and the other required parameters. 只需传入游标和其他必需参数即可。

http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_sql.htm#i1026120 http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_sql.htm#i1026120

declare
    v_sql varchar2(32767) := 'select 1 column1, 2 column2 from dual';
    v_cursor_id integer;
    v_col_cnt integer;
    v_columns dbms_sql.desc_tab;
begin
    v_cursor_id := dbms_sql.open_cursor;
    dbms_sql.parse(v_cursor_id, v_sql, dbms_sql.native);
    dbms_sql.describe_columns(v_cursor_id, v_col_cnt, v_columns);

    for i in 1 .. v_columns.count loop
        dbms_output.put_line(v_columns(i).col_name);
    end loop;

    dbms_sql.close_cursor(v_cursor_id);
exception when others then
    dbms_sql.close_cursor(v_cursor_id);
    raise;
end;
/

Output:
COLUMN1
COLUMN2

Based on dseibert 's answer, I created function for usage: 根据dseibert的回答,我创建了使用函数:

create type cols_name
    as table of varchar2(32767)
/

CREATE OR REPLACE FUNCTION GET_COLUMNS_NAME(p_selectQuery IN VARCHAR2) RETURN cols_name PIPELINED IS
    v_cursor_id integer;
    v_col_cnt integer;
    v_columns dbms_sql.desc_tab;
begin
    v_cursor_id := dbms_sql.open_cursor;
    dbms_sql.parse(v_cursor_id, p_selectQuery, dbms_sql.native);
    dbms_sql.describe_columns(v_cursor_id, v_col_cnt, v_columns);

    for i in 1 .. v_columns.count loop
        pipe row(v_columns(i).col_name);
    end loop;

    dbms_sql.close_cursor(v_cursor_id);
    return;
exception when others then
    dbms_sql.close_cursor(v_cursor_id);
    raise;
end;
/

Using it: 使用它:

select * from TABLE(get_columns_name('select 1 column1, 2 column2 from dual'));

Results: 结果:

**COLUMN_VALUE**
COLUMN1
COLUMN2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM