如何让 LIKE 子句在 ADO.NET 和 SQL Server 中工作
我正在 ASP.NET 中执行一个非常简单的查询,但是在插入 LIKE
子句后,它停止工作。
示例:
String sql = " SELECT *
FROM Products
WHERE ID = @MYID
AND Name LIKE '%@MYNAME%' ";
SqlCommand command = new SqlCommand(sql, cn);
command.Parameters.AddWithValue("@MYID", MYID.Text);
command.Parameters.AddWithValue("@MYNAME", MYNAME.Text);
如果我删除了 LIKE,它就可以工作。因此我认为它与 '' 引号有关?
I am doing a really simple query in ASP.NET, but after I inserted the LIKE
clause it stops working.
Example:
String sql = " SELECT *
FROM Products
WHERE ID = @MYID
AND Name LIKE '%@MYNAME%' ";
SqlCommand command = new SqlCommand(sql, cn);
command.Parameters.AddWithValue("@MYID", MYID.Text);
command.Parameters.AddWithValue("@MYNAME", MYNAME.Text);
If I removed the LIKE it works. Hence I am thinking its to do with the '' quotes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
原始代码混淆了SQL语句的文本和参数的内容。您的代码实际上应该如下所示:
%
符号需要成为参数值的一部分,并且在使用绑定参数时根本不需要单引号。The original code is confusing the text of the SQL statement with the content of the parameter. Your code should actually look like this:
The
%
signs need to be part of the parameter value, and you don't need the single quotes at all when using binding parameters.请注意,使用带有初始通配符的 LIKE 几乎总是一个非常糟糕的主意,因为查询不会使用该列上的任何索引。在这种情况下,您可能可以逃脱,因为看起来 ID 列上的过滤器会将您限制为一条记录,但通常您需要做的是在名称列上放置全文索引并编写如下查询这:
Just a note to say that using LIKE with an initial wildcard is almost always a very bad idea, because the query won't use any indexes on that column. In this case you can probably get away with because it looks like the filter on the ID column will limit you to one record, but generally what you need to do instead is put a full-text index on the name column and write the query like this:
或者
,当您设置 @MYNAME 参数时,适当添加“%”字符 (%SMITH%)。我认为在处理参数时不需要单引号。
Or
and when you set the @MYNAME parameter, add the "%" characters appropriately (%SMITH%). I don't think you need the single quotes when you're dealing with parameters.
不要认为使用绑定参数就像将其值插入到 SQL 字符串中一样!绑定参数值作为单独的数据发送到数据库,因此它们不能用引号引起来,也不能包含任何可选的 SQL 代码、表或列名称!
Don't think that using a bind parameter is like inserting it's value into the SQL string! Bind parameter values are sent as separate data to the DB, so they mustn't be in quotes, and neither can they contain any optional SQL code, table or column names!
传递参数值时缺少
%
符号you are missing the
%
sign while passing parameter valuesql 语句应该如下所示:
我不确定我完全理解您的评论,但您似乎想在查询中使用文本框中的值 - 也许这就是您想要做的:
“text_box”将是你的textBox控件的实际id。
The sql statement should look like this:
I am not sure I understood your comment completely, but it seems you want to use the value from a text box in your query - maybe this is what you are trying to do:
"text_box" would be the actual id of your textBox control.