Sql query with special characters - how to handle?

痴心易碎 提交于 2019-12-12 07:23:18

问题


I've few emp names like

  1. john,1
  2. devil's
  3. corn

something like this

Now when i'm searching for these names I'm using

select * from emp where empname like ('john,1,devil's,corn')

But I'm not getting expected values also I'm getting error because emp name contains special charecters like , and '.

Can someone help me out how to solve this?


回答1:


This assumes you have 3 discrete names in your example string

Exact match. you need to double up quotes.

select * from emp where
empname IN ('john,1' , 'devil''s', 'corn')

You can't LIKE/IN in SQL Server too.

select * from emp where
  empname like '%john,1%'
  OR
  empname like '%devil''s%'
  OR
  empname like '%corn%'



回答2:


For most versions of SQL, you need to escape the single quote, for example.

select * from emp where empname like ('john,1,devil''s,corn')

Also, the above example is looking for a very specific string value, you need to include * or ? as wildcard characters, so to look for all empname's like devil's, use

select * from emp where empname like '%devil''s%'

Another example

select * from emp where empname like 'john,1%'



回答3:


if you use mysql:

select * from emp where empname like ('john,1','devil\'s','corn')



回答4:


select * from emp where empname like ('john\,1','devil\'s','corn\'') escape '\'

use keyword escape to mention escape character for the query.




回答5:


If you are looking for an empname of "devil's" then I agree with the use of the escape character that Sachin and Ratinho used.

However, the like clause is used for something that is like another. For example, if you are looking for something that starts with "devil's" then you might use

select * from emp where empname like ('devil\'s%')

which would match

devil's peak
devil's beard
devil's

but not

Devil's peak
deviled eggs
devil

If you want to match an empname with "devil's" in the middle, then you might use

select * from emp where empname like ('%devil\'s%')


来源:https://stackoverflow.com/questions/4875015/sql-query-with-special-characters-how-to-handle

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