SQL LIKE for partial sentence value

167 views Asked by At

I have a database (change) which I am trying to create an sql report on the detail field value. The issue is that the detail value displays a "phrase" and I need to evaluate based on this phrase, or a part of it.

SQL

SELECT *
FROM change
WHERE change.detail LIKE '%To: [Step Two]%'

I want it to display all of the values where detail contains "To: [1. Step Two]" but the result is consistently not returning anything, where there are table values for this. Following is an example of the full value of the detail field: "[Step] Changed From: [1. Step One] To: [1. Step Two]" The items in [] represent other values in the database as well

3

There are 3 answers

1
Jim Dagg On BEST ANSWER

Presuming you're using SQL Server/TSQL, the problem you have is that the square bracket characters have a special meaning:

[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).

WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.

In order to literally match the square bracket characters, you need to escape them:

LIKE '%To: \[Step Two\]%' ESCAPE '\'
0
Daniel Gimenez On

If this is Microsoft SQL Server then you can escape brackets:

SELECT *
FROM change
WHERE change.detail LIKE '%To: \[Step Two\]%' ESCAPE '\'

Brackets used LIKE clause stand for a character range, So [Step Two] matches a character after To: that is either S,t,E,p, ,w, or o.

You can read about this on MSDN.

0
Gordon Linoff On

Part of the problem is the square brackets introduce character constants. Here is one solution:

where change.detail like '%To:  ___Step Two_%'

This just takes the risk that the square brackets are really needed for the match.

where change.detail like '%To:  __[[]Step Two]%'

An alternative is to escape those characters:

where change.detail like '%To:  __![Step Two!]%' escape '!'