問題描述
我在一個視圖中發現了這個 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 合并的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!