在我的 C# 代码中,我必须执行如下 SQL 查询:
context.ExecuteStoreQuery("SELECT * FROM MyTable WHERE Field0 = {0} AND
Field1 = {1}", field0, field1)
当 C# 中的 field1 = null 且数据库中的 field1 = NULL 时,此查询不起作用。 (我必须对 IS NULL 使用不同的语法)
如何在不使用 if 的情况下纠正此问题(实际上,我有 10 个字段...)?
最佳答案
默认情况下,SQL Server 不允许您将值与 null
进行比较。所有比较解析为 false
,甚至那些逻辑上相反的。换句话说,你可以这样做:
where field = 1
和where field <> 1
。如果field
为 null,两者逻辑上都解析为 false。
无论如何,您都需要显式检查 null
在您的查询中:
context.ExecuteStoreQuery(@"SELECT * FROM MyTable WHERE
(Field0 = {0} or (Field0 is null and {0} is null)) AND
(Field1 = {1} or (Field1 is null and {0} is null))", field0, field1)
关于c# - 带有空值的 SQL Server 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906182/