如何在 C# 命令中使用 LIKE 运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12399661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the LIKE operator in a C# Command?
提问by user1667459
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 LIKEin a command?
LIKE在命令中使用的正确方法是什么?
采纳答案by Kobi
Should be:
应该:
SELECT * FROM Contacts WHERE Name like @person + '%'
@personis a parameter - you don't need single quotes around it. You only need to concatenate it with %, which should have quotes.
@person是一个参数 - 你不需要在它周围加上单引号。您只需要将它与 连接起来%,它应该有引号。
Keep in mind:
记住:
- You could have kept it
"SELECT * FROM Contacts WHERE Name like @person", and have the parameter value contain%(concatenate in C# is simpler to understand). - You may also want to escape other wildcard characters already in the string:
%,_,[and].
- 您可以保留它
"SELECT * FROM Contacts WHERE Name like @person",并包含参数值%(C# 中的连接更容易理解)。 - 您可能还需要在字符串中已经逃脱其它通配符:
%,_,[和]。
回答by CloudyMarble
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%'would get you anything contains the 'xy'LIKE 'xy%'would get you anything starting with 'xy'
LIKE '%xy'会给你任何以'xy'结尾的东西LIKE '%xy%'会给你任何包含“xy”的东西LIKE 'xy%'会给你任何以'xy'开头的东西
回答by Shadow
Is this what you mean?
你是这个意思吗?
searchPerson.CommandText = "SELECT * FROM Contacts WHERE Name LIKE '"+person+"%'";
回答by John Woo
searchPerson.CommandText =
"SELECT * FROM Contacts WHERE Name like @person + '%'"
回答by swingNoobie
searchPerson.CommmandText = "SELECT * FROM Contacts WHERE Name like '" + @person + "%'";
回答by arun
select * from Contacts WHERE Name like '%' + '"+@person+"' + '%'
select * from Contacts WHERE Name like '%' + '"+@person+"'
select * from Contacts WHERE Name like '"+@person+"' + '%'
回答by Partha
This should work
这应该工作
"Select * from customer where FirstName LIKE '"+TextBox1.Text + '%'+ "' ";
回答by Keramat
if Field type is Nvarchar use this code:
如果字段类型是 Nvarchar 使用此代码:
"select * from Contacts where name like N'%"+person+"%'"
回答by ?mer Erhan ?zer
"SELECT * FROM table_name like concat(@persons,'%')"
"SELECT * FROM table_name like concat(@persons,'%')"
I used it.
我用过。

