列出查询的所有列(Oracle)

时间:2016-08-17 08:31:07

标签: sql oracle

Oracle中是否有SQL stmt允许我提取查询返回的所有列?

结合Java,我可以执行查询并处理元数据,但我寻找一种方便的方法。

1 个答案:

答案 0 :(得分:3)

试试这个:

DECLARE 

    sqlstr VARCHAR2(1000);
    cur INTEGER;
    columnCount INTEGER;
    describeColumns DBMS_SQL.DESC_TAB;

BEGIN 

    cur := DBMS_SQL.OPEN_CURSOR;
    sqlstr := 'SELECT * FROM TBL_A A, TBL_B B WHERE A.ID = B.ID';
    DBMS_SQL.PARSE(cur, sqlStr, DBMS_SQL.NATIVE);
    DBMS_SQL.DESCRIBE_COLUMNS(cur, columnCount, describeColumns);   
    FOR i IN 1..columnCount LOOP
        DBMS_OUTPUT.PUT_LINE ( describeColumns(i).col_name );
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR(cur);

END;

更新:要获得结果集,您可以执行以下操作:

CREATE OR REPLACE TYPE VARCHAR_TABLE_TYPE AS TABLE OF VARCHAR2(30);

CREATE OR REPLACE FUNCTION GetColumns(sqlstr IN VARCHAR2) 
   RETURN VARCHAR_TABLE_TYPE PIPELINED AS

    cur INTEGER;
    columnCount INTEGER;
    describeColumns DBMS_SQL.DESC_TAB;

BEGIN 

    cur := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE(cur, sqlStr, DBMS_SQL.NATIVE);
    DBMS_SQL.DESCRIBE_COLUMNS(cur, columnCount, describeColumns);   
    FOR i IN 1..columnCount LOOP
        PIPE ROW(describeColumns(i).col_name);
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR(cur);
   RETURN;
END;


SELECT * FROM TABLE(GetColumns('SELECT * FROM TBL_A A, TBL_B B WHERE A.ID = B.ID'));