帮助使用可能的空值对 C# 的 SQL 查询进行参数化
我需要参数化此查询的帮助。
SELECT *
FROM greatTable
WHERE field1 = @field1
AND field2 = @field2
用户应该能够搜索这 2 个字段中的任何一个,并且用户还应该能够搜索 field2 是否具有空值。
var query = "theQuery";
var cm = new SqlCommand(cn, query);
cm.AddParameter("@field1", "352515");
cm.AddParameter("@field2", DBNull.Value);
// my DataTable here is having 0 records
var dt = GetTable(cm);
[编辑]
最好的替代方案是什么?
保持 CommandText 不变,以便重用 Sql 中的计划
WHERE (field2 = @field2 OR @field2 IS NULL)
根据用户引入的值。
WHERE field2 IS NULL
我不仅仅在一个字段中思考,它可以是多种字段。
I need help with parameterizing this query.
SELECT *
FROM greatTable
WHERE field1 = @field1
AND field2 = @field2
The user should be able to search for any of the 2 fields, and the user also should be able to search if the field2 has null values.
var query = "theQuery";
var cm = new SqlCommand(cn, query);
cm.AddParameter("@field1", "352515");
cm.AddParameter("@field2", DBNull.Value);
// my DataTable here is having 0 records
var dt = GetTable(cm);
[Edit]
What is the best alternative?
Keep CommandText constant so the plan in Sql be reused
WHERE (field2 = @field2 OR @field2 IS NULL)
Change CommandText dynamically based on the values introduced by the user.
WHERE field2 IS NULL
I'm not just thinking in one field, it could be various.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 AND (@field2 IS NULL OR field2 = @field2) 使查询返回所有行,而不检查
field2
(以允许您从代码中传递 DbNull。完整的查询将如下所示:
请注意,使用此方法时可能会因索引而影响性能。看看 这篇文章了解详细信息。
You can use
AND (@field2 IS NULL OR field2 = @field2)
to make the query return all rows without checkingfield2
(to allow you to pass DbNull from your code.The complete query would be something like this:
Note that when using this method there might be a performance-hit because of indexing. Take a look at this article for details.
肮脏的方法:
isnull(field2,0) = isnull(@param2,0)
具有 isnull 永远不会出现在字段或参数中的内容
A dirty method:
isnull(field2,0) = isnull(@param2,0)
have the isnull something that would never be in the field or param
这是个好问题,但在实践中我没有时间遇到这样的问题。如果我使用
AddParameter
,那么我还会在同一代码片段中构造查询字符串。因此,如果我知道,现在我应该搜索等于 NULL 的“@field2”,我决定是否构造或
仅添加一个参数
所以我没有时间解决您所描述的问题。
更新:最好的(或唯一正确的)方法是用户输入为 NULL,您应该根据上下文来决定。在大多数情况下,不需要“AND field2 IS NULL”,但我读了你的问题,在你的特殊情况下,用户可以明确选择不是“”(空字符串),而是空值。
A good question, but in practice I had no time such problem. If I use
AddParameter
then I also construct the string for the query in the same code fragment. So if I know, that now I should search for "@field2" equal to NULL I decide whether to constructor
and add only one parameter
So I have no time the problem which you describe.
UPDATED: What is the best (or the only correct) way is users input is NULL you should decide based on the context. In the most cases "AND field2 IS NULL" is not needed, but I read your question so, that in your special case the user can explicitly choose not "" (empty string), but a NULL value.