COALESCE with NULL(与 NULL 合并)
问题描述
我在一个视图中发现了这个 SQL 片段,但我对它的用途感到相当困惑(为简洁起见,实际 SQL 已缩短):
I found this snippet of SQL in a view and I am rather puzzled by it's purpose (actual SQL shortened for brevity):
SELECT
COALESCE(b.Foo, NULL) AS Foo
FROM a
LEFT JOIN b ON b.aId=a.Id
我想不出与 null 合并的目的的单一原因,而不仅仅是这样做:
I cannot think of a single reason of the purpose of coalescing with null instead of just doing this:
SELECT
b.Foo AS Foo
FROM a
LEFT JOIN b ON b.aId=a.Id
或者至少不要显式包含 NULL:
Or at the very least don't include the NULL explicitly:
SELECT
COALESCE(b.Foo) AS Foo
FROM a
LEFT JOIN b ON b.aId=a.Id
我不知道这是谁创作的(所以我不能问),它是什么时候创作的,或者它是为哪个特定的 MS SQL Server 版本编写的(当然是 2008 年之前的版本).
I don't know who authored this (so I cannot ask), when it was authored, or for what specific MS SQL Server version it was written for (pre-2008 for sure though).
是否有任何正当理由与 NULL 合并而不是直接选择列? 我忍不住笑着把它写成菜鸟错误,但这让我想知道是否有一些我不知道的边缘案例".
Is there any valid reason to coalesce with NULL instead of just selecting the column directly? I can't help but laugh and write it off as a rookie mistake but it makes me wonder if there is some "fringe case" that I don't know about.
推荐答案
你说得对 - 没有理由使用:
You are right - there is no reason to use:
SELECT COALESCE(b.Foo, NULL)
...因为如果 b.foo 为 NULL,你不妨使用:
...because if b.foo is NULL, you might as well just use:
SELECT b.foo
...假设您想知道该值是否为空.
...assuming that you want to know if the value is null.
这篇关于与 NULL 合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:与 NULL 合并
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
