简体   繁体   中英

sql like query issue

I am trying to fetch data , which has the description keyword at the start or in the middle or at the end.

Following is my query

like '%" + description + "' or '" + description + "%' or '%" + description + "%'

Problem is it is returning irrelevant data.

Eg if i have given 'as' in description then it also choses 'cake' in result.

Description
------------------------------------------------------------
asd
asdasd
cake
Naw
Tast
ad

You can only write

like '%" + description + "%'

With this you can retrieve data that you want because it take data that start, string in the middle and finish with that string without using or statement.

just put

LIKE '%" + description + "%'

by the way, if you have multiple "or" statements, you have to rewrite the column name and the comparator

mycolumn like '%" + description + "' or
mycolumn like '" + description + "%' or 
mycolumn like '%" + description + "%'

but this isn't needed in that case.

You might also look at prepared statements !

since you have this '%" + description + "%'

why not directly

SELECT..FROM...WHERE columnName LIKE '%" + description + "%'"

buy your query is vulnerable with SQL Injection . use parameters instead

"
SELECT...
FROM...
WHERE columnName LIKE @description"

then define parameters in your query

command.Parameters.AddWithValue("@description", "%" + description + "%")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM