Select List of Column Names / Aliases from Custom Sub-Query

淺唱寂寞╮ 提交于 2019-12-11 02:27:19

问题


In Oracle, is there a way to select all the columns that are returned from a custom query with aliases? As an example, let's say we have a query as the following:

    SELECT FIRST_NAME AS COL1, LAST_NAME AS COL2, ADDRESS AS COL3
    FROM PEOPLE

I would like to know if an encapsulating query can be made that would return:

    COL1
    COL2
    COL3

回答1:


Here is how to do it in PL/SQL. Don't know if it is possible with straight oracle SQL only. You could always encapulate it in some kind of function if needed.

DECLARE
   TYPE RefCursor_Type IS REF CURSOR;

   D_RefCur             RefCursor_Type;
   D_DescriptionTable   DBMS_SQL.DESC_TAB2;
   D_ColumnCount        INTEGER;
   D_CursorHandle       INTEGER;
BEGIN
   OPEN D_RefCur
   FOR 'SELECT FIRST_NAME AS COL1, LAST_NAME AS COL2, ADDRESS AS COL3 FROM PEOPLE';

   D_CursorHandle := DBMS_SQL.to_cursor_number (D_RefCur);

   DBMS_SQL.DESCRIBE_COLUMNS2 (D_CursorHandle,
                               D_ColumnCount,
                               D_DescriptionTable);


   FOR idx IN 1 .. D_ColumnCount
   LOOP
      DBMS_OUTPUT.put_line (D_DescriptionTable (idx).col_name);
   END LOOP;
END;


来源:https://stackoverflow.com/questions/17198923/select-list-of-column-names-aliases-from-custom-sub-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!