PLSQL中的动态列别名

时间:2017-03-07 17:29:34

标签: sql oracle

有没有办法在pl / sql中动态创建别名?

我有一张表ABC

Field1    Field2   Field3  Field4
Joe       Doe      $45.00  XXX
Jane      Doe      $77.00  XXX

我创建了一个新表MY_REF

TableName   FieldName    DisplayValue
ABC         Field1       First Name
ABC         Field2       Last Name
ABC         Field3       Tax Amount

我想创建一个proc,它将获取一个表名(作为传入的参数)并使用自定义别名返回数据。

所以,如果我传入'ABC',我的最终结果将是:

First Name   Last Name  Tax Amount
Joe          Doe        $45.00
Jane         Doe        $77.00

编辑:(根据Metthew的建议尝试)

PROCEDURE GET_CUSTOM_DATA (
                             i_TableName  IN  VARCHAR2,
                             o_Refcur OUT SYS_REFCURSOR
                        )
        IS
        query_string VARCHAR2(500);
        BEGIN                       
            SELECT 'SELECT ' || listagg(fieldname || ' AS "' || displayvalue || '"',',') within group (order by null) || ' FROM ' || i_TableName
            INTO query_string
            FROM ABC
            WHERE tablename = i_TableName

            OPEN :o_Refcur FOR query_string;

        END GET_CUSTOM_DATA_DATA;

1 个答案:

答案 0 :(得分:3)

在Oracle中,必须在解析查询时定义查询中每列的数量和名称。由于您希望这些是动态的,因此您必须构建动态SQL。以下是如何使用您的数据模型的示例。

VARIABLEPRINT命令是SQL * Plus命令,此处仅用作打印结果的便捷方式。您不需要使用SQL * Plus来完成此任务。您可以改为打开PL / SQL SYS_REFCURSOR变量。

VARIABLE rc REFCURSOR

DECLARE
  p_table_name VARCHAR2(30) := 'ABC';  -- This is the parameter you pass in
  l_sql VARCHAR2(4000);
BEGIN

SELECT 'SELECT ' || listagg(fieldname || ' AS "' || displayvalue || '"',',') within group (order by null) || ' FROM ' || p_table_name
INTO   l_sql
FROM   my_ref
WHERE  tablename = p_table_name;

OPEN :rc FOR l_sql;

END;
/


PRINT rc

结果:

PL/SQL procedure successfully completed.

First Name                     Last Name                      Tax Amount
------------------------------ ------------------------------ ------------------------------
Joe                            Doe                            $45.00
Jane                           Doe                            $77.00

对错误的响应

抱歉,我似乎对SQL * Plus感到困惑。要在PL / SQL中执行此操作,您不能使用SQL * Plus绑定变量。请参阅下面的代码注释版本。

PROCEDURE GET_CUSTOM_DATA (
                         i_TableName  IN  VARCHAR2,
                         o_Refcur OUT SYS_REFCURSOR
                    )
    IS
    query_string VARCHAR2(500);
    l_rc SYS_REFCURSOR;  -- This is in place of the SQL*Plus bind variable
    BEGIN                       
        SELECT 'SELECT ' || listagg(fieldname || ' AS "' || displayvalue || '"',',') within group (order by null) || ' FROM ' || i_TableName
        INTO query_string
        FROM my_ref  -- You had this as ABC.  ABC should be the value of i_TableName
        WHERE tablename = i_TableName

        -- Open into the PL/SQL ref cursor l_rc instead of the SQL*Plus 
        -- bind variable.
        OPEN l_rc FOR query_string;

        -- NOTE: you need to do something with l_rc: pass it back to the
        -- caller or process it yourself.

    END GET_CUSTOM_DATA_DATA;