简体   繁体   中英

How to handle special characters in SQL Server Select query

I have following data in table

create table Manager(id int, managerid varchar(10) , managername varchar(50))

insert into Manager(id, managerid, managername)
values (1, 'A1', 'Mangesh'), (2, 'A''2', 'Sagar'), (3, '_C[%]3', 'Ah_mad'),
       (4, 'A4', 'Mango'), (5, 'B5', 'Sandesh')

I am using stored procedure to get the result on the basis of given characters. One of the users want to search with c[%] . I am able to handle % with [%] but if string is having [%] then I am unable to find it.

I tried with following query

declare @str varchar(100)='C[[%]'

SELECT m.* 
FROM Manager m 
WHERE m.managerid LIKE '%'+@str+'%'

This way I am able to get the result but in this case input is C[% only. I replaced % with [%] in my stored procedure parameter. But if input is C[%] then my query is not returning anything.

You have to escape the square bracket and % character using [] , this tells SQL to treat them as literals.

So in order to find the % it needs escaped as [%] , the same for the square bracket it needs escaped as [[]

You don't need to escape the ] because if it's not paired with [ has no special meaning.

select * from Manager where managerid like '%c[[][%]]%'

Use Escape to ignore the wildcards . Try this

select * from Manager 
where managerid like '%c\[%]%' escape '\'

您只需要转义一个开头的'['

SELECT * FROM MANAGER where managerid like '%_C[[%]%'

Both % , _ and [ are special characters and should be escaped. So it could be that even your INSERT-statement is wrong.

You can place the special characters between square brackets [ and ] to make them literal.

insert into Manager(id,managerid,managername)values(3,'[_]C[[][%]]3','Ah[_]mad')

You can use this same method to search on:

SELECT * FROM Manager
WHERE managerid LIKE '%C[[][%]]%'

Or define your own escape character like this:

SELECT * FROM Manager
WHERE managerid LIKE '%C\[\%]%' ESCAPE '\'

Here is some documentation that might be usefull to you: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql

In case you are trying to searching with input 'C[%]' . Check this answer,

declare @str varchar(100)='C[%]'

SELECT m.* 
FROM Manager m 
WHERE REPLACE(m.managerid,'[','')    LIKE  '%'+@str+'%'

I got the solution.

declare @str varchar(100)='C\[\%]'

SELECT m.* 
FROM Manager m 
WHERE m.managerid LIKE '%'+@str+'%' ESCAPE '\'

It worked.

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