1

I have a search box where user enters anything in textbox and submits.Lets say user enters Peter.If we are comparing in sql table with following query

select * from xml where name like '%peter%'

This query works well,but when i want to search for only peter in the string,then it creates a problem.Like when i want to search for only those rows which are having Peter present in the name column. in name column,value 1-My name is Peter. valu2-My name is Peterwatter. valu3-My name is Peter living in US. when i want to search it should give only first and third row.not the second one.BUt with above query i m getting all the three rows.How can i correct that.Please guide on this

1
  • 1
    @Mihai why wouldn't this return the second one? Commented Apr 28, 2014 at 17:11

4 Answers 4

3
select * from xml 
 where name like '%peter'
    or name like '%peter %'
Sign up to request clarification or add additional context in comments.

Comments

1

There is a way to do so with regular expressions, but a simple solutions can be like this:

[name] like '% peter %' 
or [name] like '% peter' 
or [name] like 'peter %' 
or [name] = 'peter'

Comments

0

try like '% peter %' (with spaces after/before the wild cards) However please watch out for sql injections. http://en.wikipedia.org/wiki/SQL_injection

12 Comments

Would this not select all three values? Are you sure?
will this b prone to sql injection attacks sir.if we dont escape characters sir.
@Hituptony actually i have a mistake and it will only select row 3 since there is not a space after peter. Seems that coder's answer above is better.
@user3575612 this type of query is prone to sql injection because you are taking user input and passing it to the database. perhaps you can paramatize the query and turn it into a stored procedure.
There is a period after 'My name is Peter.'
|
0
select * from xml 
 or name like '%Peter.'
 or name like 'Peter%'
 or name like 'Peter %'
 or name like '% Peter.'
 or name like '% Peter %'

Edit:: Now it will.

1 Comment

Will this exclude the second value? 1-My name is Peter. valu2-My name is Peterwatter. valu3-My name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.