【问题标题】:Function which renames its output parameters, according to some input parameters (prefix/suffix)根据一些输入参数(前缀/后缀)重命名其输出参数的函数
【发布时间】:2016-08-09 16:13:12
【问题描述】:

我想要一个可以根据一些输入参数重命名其输出参数的函数。

我尝试了一些解决方案来自动执行此任务(主要集中在changing return type for function to polymorphic record variable),但都不适合我。我会很感激任何建议。

这个问题让我发疯,因为我当前的设置让我编写了大量不必要的(?)代码。 我使用这种函数来格式化视图中显示的日期,所以它应该是/dynamic/。

我现在的设计是这样的:

CREATE OR REPLACE FUNCTION name_of(
    IN in_date date, 
    OUT mnth_date text,
    OUT qrt_date text
) AS
$func$
    BEGIN
        mnth_date =to_char(in_date ,'YYYY"M"MM');       
        qrt_date =to_char(in_date ,'YYYY"Q"Q'); 
    END
$func$ LANGUAGE plpgsql;

有什么结果:

select (name_of('2014-04-30')).*


________________________
|mnth_date  |qrt_date  |
------------------------
|2014M04    |2014Q2    |

我的目标设置是得到类似这样的结果:

    select 
        A.*, B.*
     from
        name_of('2014-04-30','foo_prefix' ) A,
        name_of('2014-05-13','creation' ) B;

__________________________________________________________________________________________________
|foo_prefix_mnth_date   |foo_prefix_qrt_date    |creation_mnth_date     |creation_qrt_date      |
--------------------------------------------------------------------------------------------------
|2014M04                |2014Q2                 |2014M05                |2014Q2                 |

目前我大量使用别名,所以我的代码看起来类似于:

    select 
        A.mnth_date foo_prefix_mnth_date,
        A.qrt_date foo_prefix_qrt_date,
        B.mnth_date creation_mnth_date,
        B.qrt_date creation_qrt_date
     from
        name_of('2014-04-30') A,
        name_of('2014-05-13') B;

【问题讨论】:

    标签: sql postgresql stored-procedures plpgsql


    【解决方案1】:

    使用列aliases

    SELECT
        name_of('2014-04-30') AS foo_prefix_mnth_date,
        name_of('2014-05-13') AS creation_mnth_date,
        name_of('2014-06-20') AS access_mnth_date;
    

    关键字AS 是可选的,所以这也有效:

    SELECT name_of('2014-04-30') foo_prefix_mnth_date;
    

    但建议使用它以获得更好的可读性

    【讨论】:

    • 谢谢。我愿意,但我想放弃这种方法,因为它无效。我更新了我的问题以更好地描述问题。
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多