如何处理 WHERE 子句中的 NULL 值并根据遇到的情况更改目标列
How to handle NULL values in WHERE clause and change target column based upon its encounter
我需要 WHERE 子句来更改遇到 NULL 时正在评估的列。例如我正在尝试做这样的事情:
SELECT *
FROM customer c
WHERE CASE WHEN c.cust_id_1(@variable) IS NOT NULL THEN c.cust_id_1 = @variable
ELSE CASE WHEN c.cust_id_2(@variable) IS NOT NULL THEN c.cust_id_2 = @variable
ELSE c.cust_id_3 = @variable
这样的事情可能吗? 3 个 cust_id 之一不会为 NULL。
你不需要 CASE
表达式,你只需要逻辑运算符
SELECT *
FROM customer c
WHERE
(c.cust_id_1 IS NOT NULL AND c.cust_id_1 = @variable)
OR
(c.cust_id_2 IS NOT NULL AND c.cust_id_2 = @variable)
OR
(c.cust_id_3 IS NOT NULL AND c.cust_id_3 = @variable)
这似乎不是最佳 table 设计,但这不是您想要的简单 COALESCE
吗?
WHERE @variable = COALESCE(cust_id_1, cust_id_2, cust_id_3);
我需要 WHERE 子句来更改遇到 NULL 时正在评估的列。例如我正在尝试做这样的事情:
SELECT *
FROM customer c
WHERE CASE WHEN c.cust_id_1(@variable) IS NOT NULL THEN c.cust_id_1 = @variable
ELSE CASE WHEN c.cust_id_2(@variable) IS NOT NULL THEN c.cust_id_2 = @variable
ELSE c.cust_id_3 = @variable
这样的事情可能吗? 3 个 cust_id 之一不会为 NULL。
你不需要 CASE
表达式,你只需要逻辑运算符
SELECT *
FROM customer c
WHERE
(c.cust_id_1 IS NOT NULL AND c.cust_id_1 = @variable)
OR
(c.cust_id_2 IS NOT NULL AND c.cust_id_2 = @variable)
OR
(c.cust_id_3 IS NOT NULL AND c.cust_id_3 = @variable)
这似乎不是最佳 table 设计,但这不是您想要的简单 COALESCE
吗?
WHERE @variable = COALESCE(cust_id_1, cust_id_2, cust_id_3);