如果文字不包含通配符,我不能用 col <> 文字替换 ISNULL(col, literal) NOT LIKE 文字的任何原因?

Any reasons why I can't replace ISNULL(col, literal) NOT LIKE literal with col <> literal if literal contains no wildcards?

我遇到过一些旧代码,比如这个例子:

    DECLARE @tmpVal INT = 999

    DECLARE @tmpTable TABLE (col1 INT, col2 VARCHAR(20))

    INSERT INTO @tmpTable (col1, col2)
    VALUES 
        (1, 'Do not want this'),
        (2, 'Happy with this'),
        (3, NULL)

    SELECT
        col1,
        col2,
        -- I see code like this
        CASE
            WHEN ISNULL(col2, 'Do not want this') NOT LIKE 'Do not want this'
            THEN @tmpVal
        END                                                 AS CurrentCol,

        -- can I replace it with code like this because there is no else?
        CASE
            WHEN col2 <> 'Do not want this'
            THEN @tmpVal
        END                                                 AS BetterCol

    FROM 
        @tmpTable

我的想法是 ISNULL(col2, 'Do not want this') NOT LIKE 'Do not want this' 应该替换为 col2 <> 'Do not want this',因为它可以完美地处理 null 情况。

我可以使用 BetterCol 中的表单而不是 CurrentCol 作为 WHEN 表达式吗?如果不能,为什么?有没有我没有看到的极端情况?

TL;DR; - 是的,您可以更换它 - 它(几乎)绝对安全。

较长的版本:

在 SQL 服务器中,除非指定了 SET ANSI_NULL OFF(而且它真的不应该被指定 - 请注意它已被弃用) - 任何与 null 的比较都会UNKNOWN 的结果基本上等同于 case 表达式或 where 子句谓词的 false

这意味着SomeValue <> NULLSomeValue = NULL甚至NULL = NULLNULL <> NULL都将returnUNKNOWN

虽然我没有找到任何关于 NULLLIKE 运算符行为的文档(我在 SET ANSI_NULLLIKE and NULL and UNKNOWN 文档中搜索过)它众所周知,nulllike 运算符的行为与 = 运算符的行为相同 - 意味着 NULL LIKE 'some string' 将 return UNKNOWN 还有。