SQL在串联上使用If Not Null [英] SQL using If Not Null on a Concatenation

查看:287
本文介绍了SQL在串联上使用If Not Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有桌子

SELECT (Firstname || '-' || Middlename || '-' || Surname)  AS example_column
FROM example_table

这将显示Firstname-Middlename-Surname例如

This will display Firstname-Middlename-Surname e.g.

John--Smith
Jane-Anne-Smith

第二个(简)显示正确,但是由于John没有中间名,因此我希望它忽略第二个破折号。

The second one (Jane’s) displays correct, however since John doesn’t have a middlename, I want it to ignore the second dash.

我该如何放置一种IF Middlename = NULL语句,以便只需显示John-Smith

How could I put a sort of IF Middlename = NULL statement in so that it would just display John-Smith

推荐答案

这是我的建议:

PostgreSQL和其他SQL数据库,其中'a'|| NULL是NULL ,然后使用 COALESCE

PostgreSQL and other SQL databases where 'a' || NULL IS NULL, then use COALESCE:

SELECT firstname || COALESCE('-' || middlename, '') || '-' || surname ...

Oracle和其他SQL数据库,其中'a'|| NULL ='a'

Oracle and other SQL databases where 'a' || NULL = 'a':

SELECT first name || DECODE(middlename, NULL, '', '-' || middlename) || '-' || surname...

我想简洁。在这里,对于任何维护程序员来说,中间名是否为空都不是一件很有趣的事情。 CASE开关非常好,但是体积很大。我想避免在可能的地方重复相同的列名(中间名)。

I like to go for conciseness. Here it is not very interesting to any maintenance programmer whether the middle name is empty or not. CASE switches are perfectly fine, but they are bulky. I'd like to avoid repeating the same column name ("middle name") where possible.

正如@Prdp所指出的,答案是RDBMS特定的。具体的是服务器是否将零长度字符串视为与 NULL 等效,从而确定是否连接 NULL 是否会产生 NULL

As @Prdp noted, the answer is RDBMS-specific. What is specific is whether the server treats a zero-length string as being equivalent to NULL, which determines whether concatenating a NULL yields a NULL or not.

通常 COALESCE 对于PostgreSQL样式的空字符串处理最简洁,对于Oracle样式的空字符串处理, DECODE(* VALUE *,NULL,''... 是最简洁的。

Generally COALESCE is most concise for PostgreSQL-style empty string handling, and DECODE (*VALUE*, NULL, ''... for Oracle-style empty string handling.

这篇关于SQL在串联上使用If Not Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆