首页 > 解决方案 > 简单的字符串返回函数,默认参数为 NULL,返回 NULL 而不是字符串

问题描述

我有以下功能:

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?

标签: postgresqloptional-parameterspostgresql-9.6null-string

解决方案


这并不神秘 - 对 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 并且更具侵略性。


推荐阅读