3

I have a query that looks a bit like this:

SELECT * FROM Stuff WHERE name LIKE '[a\]]%'

My goal is to match all names starting with a or ] (closed bracket). However, this seems to match everything starting with a] or \\].

Is this possible without OR, a lot of auto-generated LIKEs?

2
  • Just want to understand is there any problem to use LIKE multiple times i.e name LIKE 'a%' or (name LIKE ']%') Oct 9, 2019 at 11:19
  • @ShekarKola My actual command has over 40 possible characters, so that would be a pretty long query. Oct 9, 2019 at 12:01

1 Answer 1

2

You have to escape the ]. That means before any character you want to literally search for, example % or _ or ], you have to add an escape character. For example \% to search for a literal %

Example:

CREATE TABLE #Test( text varchar(50) )

INSERT INTO #test  VALUES (']'),('atest'),('zz')

SELECT * FROM #test  WHERE text LIKE '[a\]]%' {escape '\'}

To read more about escape chars in LIKE, you can check :

LIKE Predicate Escape Character

You can also test it using SQL fiddle: SQL Fiddle

6
  • I escaped it in the query in my question. It doesn't work. Oct 9, 2019 at 10:29
  • Check my example or the link, you have to add : {escape '\'} Oct 9, 2019 at 10:35
  • Hi @YannickLiekens, seems your example can only retrieves the rows that are starting with only a]. Cannot retrieves text starting with a which mentioned in OP Oct 9, 2019 at 11:18
  • @ShekarKola Seems to be working fine? Added a SQL Fiddle link. Oct 9, 2019 at 11:26
  • Hi @YannickLiekens, Fiddle got one "\" and your example got two "\\". Anyway, it works with one escape character Oct 9, 2019 at 11:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.