简体   繁体   English

当字段具有NULL值时,SQL WHERE子句不返回行

[英]SQL WHERE clause not returning rows when field has NULL value

Ok, so I'm aware of this issue: 好的,所以我知道这个问题:

When SET ANSI_NULLS is ON, all comparisons against a null value evaluate to UNKNOWN 当SET ANSI_NULLS为ON时,对空值的所有比较均得出UNKNOWN

However, I am trying to query a DataTable . 但是,我试图查询一个DataTable

I could add to my query: 我可以添加到我的查询:

OR col_1 IS NULL OR col_2 IS NULL

for every column, but my table has 47 columns, and I'm building dynamic SQL (string concatenation), and it just seems like a pain to do that. 对于每列,但我的表有47列,并且我正在构建动态SQL(字符串串联),这样做似乎很痛苦。 Is there another solution? 还有其他解决方案吗?

I was to bring back all the rows that have NULL values in the WHERE comparison. 我要带回WHERE比较中所有具有NULL值的行。

UPDATE 更新

Example of query that gave me problems: 给我带来问题的查询示例:

string query = col_1 not in ('Dorothy', 'Blanche') and col_2 not in ('Zborna', 'Devereaux')
grid.DataContext = dataTable.Select(query).CopyToDataTable();

(didn't retrieve rows if/when col_1 = null and/or col_2 = null ) (如果/当col_1 = null和/或col_2 = null时,不检索行)

So you mean something like (example with 2 columns) 所以你的意思是(例如2列示例)

WHERE (col1 = 'abc' or col1 is null)
  AND (col2 = 3 or col2 is null)

But you want to include the nulls always? 但是您想始终包含空值吗? This should work 这应该工作

WHERE isnull(col1,'abc') = 'abc'
  AND isnull(col2, 3) = 3

Are you doing this because you want to get the NULL values, or because you don't want the NULL values to interfere with your comparisons? 您这样做是因为要获取NULL值,还是因为不想让NULL值干扰比较?

For example, this: 例如,这:

WHERE col_1 != 'John'

will not return any rows for which col_1 is NULL (you've indicated in your question that you know this). 不会返回col_1为NULL的任何行(您在问题中已表明您知道这一点)。

If you're trying to get the col_1 IS NULL rows to return with a WHERE clause like the above, you have two options in MS SQL (one in mySql). 如果要像上面一样通过WHERE子句返回col_1 IS NULL行,则在MS SQL中有两个选项(一个在mySql中)。

In both MS SQL and mySql, the coalesce() function will allow you to do a comparison of this sort. 在MS SQL和mySql中, coalesce()函数都允许您进行这种比较。 In MS SQL (I believe this is the same for mySql, too), its function is to take two or more arguments, and evaluate them in order, returning the first non-NULL one it finds. 在MS SQL中(我相信mySql也是如此),其功能是接受两个或更多参数,并对它们进行顺序求值,并返回找到的第一个非NULL参数。 In MS SQL, there's a shorthand function called isNull() , which is like coalesce() but only takes two parameters. 在MS SQL中,有一个叫做isNull()的简写函数,它类似于coalesce()但只需要两个参数。

In the above example, you would do the following: 在上面的示例中,您将执行以下操作:

WHERE coalesce(col_1,'') != 'John'

and that would return rows that have col_1 IS NULL as well as rows that have non-NULL values in col_1 which do not equate to 'John'. 并且将返回col_1 IS NULL的行以及col_1中不等于“ John”的非NULL值的行。

If this is your real goal, then this technique should work for you. 如果这是您的真正目标,那么此技术应该为您工作。

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

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