How to use the LIKE operator in a C# Command?

懵懂的女人 提交于 2020-01-04 02:12:06

问题


I need to insert a string into an Sql Command

search.CommandText = "SELECT * FROM Contacts WHERE Name like ' + @person + % + '";

What it the right way of using LIKE in a command?


回答1:


Should be:

SELECT * FROM Contacts WHERE Name like @person + '%'

@person is a parameter - you don't need single quotes around it. You only need to concatenate it with %, which should have quotes.

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 ].



回答2:


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'



回答3:


Is this what you mean?

searchPerson.CommandText = "SELECT * FROM Contacts WHERE Name LIKE '"+person+"%'";



回答4:


searchPerson.CommandText =  
   "SELECT * FROM Contacts WHERE Name like @person + '%'"



回答5:


searchPerson.CommmandText = "SELECT * FROM Contacts WHERE Name like '" + @person + "%'";



回答6:


select * from Contacts WHERE Name like '%' + '"+@person+"' + '%' 
select * from Contacts WHERE Name like '%' + '"+@person+"' 
select * from Contacts WHERE Name like '"+@person+"' + '%'



回答7:


This should work

"Select *  from customer where FirstName LIKE '"+TextBox1.Text + '%'+ "'   ";



回答8:


if Field type is Nvarchar use this code:

   "select * from Contacts where name like N'%"+person+"%'"



回答9:


"SELECT * FROM table_name like concat(@persons,'%')"

I used it.



来源:https://stackoverflow.com/questions/12399661/how-to-use-the-like-operator-in-a-c-sharp-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!