85

I stumbled into a delicate SQL problem when I needed to use a value from a field inside a LIKE %..% statement.

Example:

SELECT t1.Notes, t2.Name
FROM Table1 t1, Table2 t2
WHERE t1.Notes LIKE '%t2.Name%'

This is only an example from the top of my head to show what I need to do (I know this will not work). I need to use the value of t2.Name inside the LIKE %..%

I guess this is trivial when you know it ;)

2 Answers 2

183

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that did the trick! Aa I said, it is trivial when you know it. However, I stumbled into the next problem... But I will make a new question. Thank you!
Any solution for all databases?
Any Solution to use LIKE %..% with field in IF statement?
Technically you might want to escape the field in case it has % in it: LIKE CONCAT('%',REPLACE(field,'%','\%'),'%')
-8
  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

Comments

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.