[英]How to use the LIKE operator in a C# Command?
I need to insert a string into an Sql Command 我需要在Sql命令中插入一个字符串
search.CommandText = "SELECT * FROM Contacts WHERE Name like ' + @person + % + '";
What it the right way of using LIKE
in a command? 在命令中使用LIKE
的正确方法是什么?
Should be: 应该:
SELECT * FROM Contacts WHERE Name like @person + '%'
@person
is a parameter - you don't need single quotes around it. @person
是一个参数 - 你不需要单引号。 You only need to concatenate it with %
, which should have quotes. 你只需要将它与%
连接,它应该有引号。
Keep in mind: 记住:
"SELECT * FROM Contacts WHERE Name like @person"
, and have the parameter value contain %
(concatenate in C# is simpler to understand). 你可以保留它"SELECT * FROM Contacts WHERE Name like @person"
,并让参数值包含%
(C#中的concatenate更容易理解)。 %
, _
, [
and ]
. 您可能还想要转义字符串中已有的其他通配符: %
, _
, [
和]
。 Use Syntax: 使用语法:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
The "%"
sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern. "%"
符号可用于在模式之前和之后定义通配符(模式中缺少字母)。
For Example: 例如:
LIKE '%xy'
would get you anything ending with 'xy' LIKE '%xy'
会以'xy'结尾 LIKE '%xy%'
would get you anything contains the 'xy' LIKE '%xy%'
会得到任何包含'xy'的内容 LIKE 'xy%'
would get you anything starting with 'xy' LIKE 'xy%'
会给你带来任何以'xy'开头的东西 你是这个意思吗?
searchPerson.CommandText = "SELECT * FROM Contacts WHERE Name LIKE '"+person+"%'";
searchPerson.CommandText =
"SELECT * FROM Contacts WHERE Name like @person + '%'"
searchPerson.CommmandText = "SELECT * FROM Contacts WHERE Name like '" + @person + "%'";
select * from Contacts WHERE Name like '%' + '"+@person+"' + '%'
select * from Contacts WHERE Name like '%' + '"+@person+"'
select * from Contacts WHERE Name like '"+@person+"' + '%'
这应该工作
"Select * from customer where FirstName LIKE '"+TextBox1.Text + '%'+ "' ";
如果Field类型为Nvarchar,请使用以下代码:
"select * from Contacts where name like N'%"+person+"%'"
"SELECT * FROM table_name like concat(@persons,'%')" “SELECT * FROM table_name like concat(@persons,'%')”
I used it. 我用过它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.