【发布时间】:2019-06-10 01:31:58
【问题描述】:
我遇到过一些旧代码,类似于这个例子:
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 表达式吗?如果不是,为什么?有没有我没有看到的边缘案例?
【问题讨论】:
-
很少使用没有
%、_等特殊字符的LIKE。确保没有特殊字符,这样您就可以安全地替换表达式。您还可能从索引中受益,因为ISNULL会因为将函数应用于跟踪列而使它们的使用无效。