简体   繁体   English

SQL Server where子句中的where列为null

[英]SQL Server where column in where clause is null

Let's say that we have a table named Data with Id and Weather columns. 假设我们有一个名为IdWeather列的Data表。 Other columns in that table are not important to this problem. 该表中的其他列对于此问题并不重要。 The Weather column can be null. Weather列可以为空。

I want to display all rows where Weather fits a condition, but if there is a null value in weather then display null value. 我想显示Weather符合条件的所有行,但是如果weather有空值,则显示空值。

My SQL so far: 到目前为止,我的SQL:

SELECT * 
FROM Data d
WHERE (d.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%' OR d.Weather IS NULL)

My results are wrong, because that statement also shows values where Weather is null if condition is not correct (let's say that users mistyped wrong). 我的结果是错误的,因为如果条件不正确,该语句还会显示Weather为null的值(假设用户键入错误)。

I found similar topic, but there I do not find appropriate answer. 我找到了类似的主题,但是找不到合适的答案。 SQL WHERE clause not returning rows when field has NULL value 当字段具有NULL值时,SQL WHERE子句不返回行

Please help me out. 请帮帮我。

Your query is correct for the general task of treating NULL s as a match. 对于将NULL视为匹配项的一般任务,您的查询是正确的。 If you wish to suppress NULL s when there are no other results, you can add an AND EXISTS ... condition to your query, like this: 如果希望在没有其他结果时抑制NULL ,则可以在查询中添加AND EXISTS ...条件,如下所示:

SELECT * 
FROM Data d
WHERE d.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%'
   OR (d.Weather IS NULL AND EXISTS (SELECT * FROM Data dd WHERE dd.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%'))

The additional condition ensures that NULL s are treated as matches only if other matching records exist. 附加条件确保仅当存在其他匹配记录时,才将NULL视为匹配项。

You can also use a common table expression to avoid duplicating the query, like this: 您还可以使用公用表表达式来避免重复查询,如下所示:

WITH cte (id, weather) AS
(
    SELECT * 
    FROM Data d
    WHERE d.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%'
)
SELECT * FROM cte
UNION ALL
SELECT * FROM Data WHERE weather is NULL AND EXISTS (SELECT * FROM cte)

statement show also values where Wether is null if condition is not correct (let say that users typed wrong sunny). 语句还显示如果条件不正确的情况下Wether为null的值(假设用户输入的sunny错误)。

This suggests that the constant 'sunny' is coming from end-user's input. 这表明恒定的'sunny'来自最终用户的输入。 If that is the case, you need to parameterize your query to avoid SQL injection attacks . 在这种情况下,您需要参数化查询以避免SQL注入攻击

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM