在 SQL Server 2008R2 中重寫 IS DISTINCT FROM 運算子
SQL Server 2008R2 不支援標準的 IS DISTINCT FROM 和 IS NOT DISTINCT FROM 運算子。本文提供了一種解決方案,使用與該軟體版本相容的替代語法來重寫這些表達式。
IS DISTINCT FROM
如果兩個值不相等或其中一個值為 NULL,則 IS DISTINCT FROM 謂詞計算結果為 True;如果它們相等且都不為 NULL,則計算結果為 False。它可以改寫如下:
<code class="language-sql">((a != b OR a IS NULL OR b IS NULL) AND NOT (a IS NULL AND b IS NULL))</code>
範例:
<code class="language-sql">SELECT CASE WHEN (a != b OR a IS NULL OR b IS NULL) AND NOT (a IS NULL AND b IS NULL) THEN 'True' ELSE 'False' END AS DistinctResult</code>
IS NOT DISTINCT FROM
IS NOT DISTINCT FROM 運算子在兩個值相等或皆為 NULL 時計算結果為 True,在它們不相等且不皆為 NULL 時計算結果為 False。它可以改寫為:
<code class="language-sql">(NOT (a != b OR a IS NULL OR b IS NULL) OR (a IS NULL AND b IS NULL))</code>
範例:
<code class="language-sql">SELECT CASE WHEN (NOT (a != b OR a IS NULL OR b IS NULL) OR (a IS NULL AND b IS NULL)) THEN 'True' ELSE 'False' END AS NotDistinctResult</code>
注意:
提供的重寫確保結果始終為 True 或 False,避免了帶有 NULL 運算元時可能出現的 Unknown 狀態。
以上是如何在 SQL Server 2008R2 中重寫 IS DISTINCT FROM 和 IS NOT DISTINCT FROM 運算子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!