带有空值的 SQL Server 查询
在我的 C# 代码中,我必须执行如下 SQL 查询:
context.ExecuteStoreQuery("SELECT * FROM MyTable WHERE Field0 = {0} AND
Field1 = {1}", field0, field1)
当 C# 中的 field1 = null 且数据库中的 NULL 时,此查询不起作用。 (我必须对 IS NULL 使用不同的语法)
如何在不使用 if 的情况下纠正这个问题(实际上,我有 10 个字段......)?
In my C# code, I have to do an SQL Query like this :
context.ExecuteStoreQuery("SELECT * FROM MyTable WHERE Field0 = {0} AND
Field1 = {1}", field0, field1)
When field1 = null in c# and NULL in database this query doesn't work. (I have to use a different syntax with IS NULL)
How can I correct this without make an if (in reality, I have 10 fields...) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
默认情况下,SQL Server 不允许您将值与
null
进行比较。所有比较都解析为false
,即使是逻辑上相反的比较。换句话说,您可以执行以下操作:where field = 1
和where field <> 1.
.如果field
为 null,则两者在逻辑上都解析为 false。无论如何,您需要在查询中显式检查
null
:By default, SQL server does not allow you to compare a value to
null
. All comparisons resolve tofalse
, even those that are logically opposite. In other words, you can do:where field = 1
andwhere field <> 1
. Iffield
is null, both logically resolve to false.In any case, you need an explicit check for
null
in your query:希望您可以添加简单的逻辑来自己添加“WHERE”或“AND”。
Hope you can add simple logic to add "WHERE" or "AND" by yourself.
好吧,我要做的第一件事就是删除 select *.坏的!
我要做的第二件事是将其设为存储过程。
然后你可以将你的代码更改为这样
well, the first thing i would do is remove the select *. BAD!
the second thing i would do is make this a stored procedure.
you then can change your code to this
您可以使用 if 语句的简短变体。
我认为如果没有 if 语句你就无法解决你的问题。
示例:
还可以使用“@ParameterName”对查询进行参数
化
you can use the short variant of the if statement.
I don't think you can handle your problem without an if statement.
Example:
It is also possible to parameterize the query by using "@ParameterName"
Regards