postgresql - 简单的字符串返回函数,默认参数为 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?
解决方案
这并不神秘 - 对 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 并且更具侵略性。
推荐阅读
- python - Python 3.6:使用另一个值作为索引创建新字典
- c - 使用 OpenSSL 1.1 API 解析“其他”ASN.1 类型
- scala - 有条件地使用类似构建器的函数
- jquery - 扩展过滤控制,不设置搜索字段
- javascript - 绕过一个特定 div JS (iOS) 上的文档滚动锁定
- spring-boot - 如何使用 Spring Cloud Vault 检索数据库凭据
- angular - 为什么在 Angular 6 中构建项目时会抛出错误?
- margin - 图像下的 Bootstrap 4 奇怪的边距
- c++ - 模板类的唯一容器
- javascript - React Semantic Ui 下拉列表动态设置