【问题标题】:Simple string return function with default param passed as NULL, returns NULL instead of string简单的字符串返回函数,默认参数为 NULL,返回 NULL 而不是字符串
【发布时间】:2018-05-25 23:35:10
【问题描述】:

我有以下功能:

CREATE OR REPLACE FUNCTION public.get_string(cmd_type text, udf_name text, 
group_name character varying DEFAULT 'usage'::character varying)
 RETURNS text
 LANGUAGE plpgsql
 AS $function$ 
BEGIN
 return 'This is the string: '''|| group_name ||''''::text;
END;
$function$

当我这样称呼它时:

select public.get_string('test', 'myudf!', group_name=>null::character varying); 

它返回 NULL。

我希望它至少会返回:

This is the string: ''

但是,当我这样称呼它时:

select public.get_string('test', 'myudf!');

我得到了预期:

This is the string: 'usage'

为什么将 NULL 传递给可选参数会使整个字符串为 NULL?

【问题讨论】:

    标签: postgresql optional-parameters postgresql-9.6 null-string


    【解决方案1】:

    这并不神秘 - 对 NULL 值的任何操作再次为 NULL。

    postgres=# select ('Hello' || null) is null ;
    ┌──────────┐
    │ ?column? │
    ╞══════════╡
    │ t        │
    └──────────┘
    (1 row)
    

    您应该使用 coalesce 函数并针对 NULL 值清理表达式。

    postgres=# select ('Hello' || coalesce(null,'')) ;
    ┌──────────┐
    │ ?column? │
    ╞══════════╡
    │ Hello    │
    └──────────┘
    (1 row)
    

    也许您知道一个 Oracle 数据库,其中 NULL 和空字符串是相等的。但是只有Oracle才这样,其他地方NULL就是NULL,而且更具侵略性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2012-10-09
      • 2011-05-18
      • 2013-10-31
      • 2019-09-04
      • 1970-01-01
      相关资源
      最近更新 更多