NVL2 函数 - Amazon Redshift
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

NVL2 函数

根据指定表达式的计算结果是 NULL 还是 NOT NULL 返回这两个值之一。

语法

NVL2 ( expression, not_null_return_value, null_return_value )

参数

expression

一个要针对 null 状态进行计算的表达式,如列名称。

not_null_return_value

expression 的计算结果为 NOT NULL 时返回的值。not_null_return_value 值必须具有与 expression 相同的数据类型或可隐式转换为该数据类型。

null_return_value

expression 的计算结果为 NULL 时返回的值。null_return_value 值必须具有与 expression 相同的数据类型或可隐式转换为该数据类型。

返回类型

按以下方式确定 NVL2 返回类型:

  • 如果 not_null_return_valuenull_return_value 为 null,则返回非 null 表达式的数据类型。

如果 not_null_return_valuenull_return_value 都不为 null:

  • 如果 not_null_return_valuenull_return_value 具有相同的数据类型,则返回该数据类型。

  • 如果 not_null_return_valuenull_return_value 具有不同的数字数据类型,则返回最小的可兼容数字数据类型。

  • 如果 not_null_return_valuenull_return_value 具有不同的日期时间数据类型,则返回时间戳数据类型。

  • 如果 not_null_return_valuenull_return_value 具有不同的字符数据类型,则返回 not_null_return_value 的数据类型。

  • 如果 not_null_return_valuenull_return_value 具有混合的数字和非数字数据类型,则返回 not_null_return_value 的数据类型。

重要

在最后两个示例中(其中返回 not_null_return_value 的数据类型),null_return_value 将隐式转换为该数据类型。如果数据类型不兼容,则该函数将失败。

使用说明

expressionsearch 参数均为 null 时,DECODE 函数 可以通过与 NVL2 类似的方式使用。区别在于:在 DECODE 中,返回内容将同时具有 result 参数的值和数据类型。相反,在 NVL2 中,返回内容将具有 not_null_return_valuenull_return_value 参数的值(不管函数选择哪一个),但将具有 not_null_return_value 的数据类型。

例如,假定 column1 为 NULL,则以下查询将返回相同的值。但是,DECODE 返回值数据类型将为 INTEGER,NVL2 返回值数据类型将为 VARCHAR。

select decode(column1, null, 1234, '2345'); select nvl2(column1, '2345', 1234);

示例

以下示例修改一些示例数据,然后计算两个字段以为用户提供相应的联系人信息:

update users set email = null where firstname = 'Aphrodite' and lastname = 'Acevedo'; select (firstname + ' ' + lastname) as name, nvl2(email, email, phone) AS contact_info from users where state = 'WA' and lastname like 'A%' order by lastname, firstname; name contact_info --------------------+------------------------------------------- Aphrodite Acevedo (906) 632-4407 Caldwell Acevedo Nunc.sollicitudin@Duisac.ca Quinn Adams vel@adipiscingligulaAenean.com Kamal Aguilar quis@vulputaterisusa.com Samson Alexander hendrerit.neque@indolorFusce.ca Hall Alford ac.mattis@vitaediamProin.edu Lane Allen et.netus@risusDonec.org Xander Allison ac.facilisis.facilisis@Infaucibus.com Amaya Alvarado dui.nec.tempus@eudui.edu Vera Alvarez at.arcu.Vestibulum@pellentesque.edu Yetta Anthony enim.sit@risus.org Violet Arnold ad.litora@at.com August Ashley consectetuer.euismod@Phasellus.com Karyn Austin ipsum.primis.in@Maurisblanditenim.org Lucas Ayers at@elitpretiumet.com