Search code examples
sql-servert-sqlsql-likeequality

Is there an exact string compare in T-SQL?


I have searched many answers, but I have not found a solution for the following simple task:

I have a lengthy TextString and want to look for an exact match to the string ' Text ' within it.

TextString LIKE '% Text %'

gives all occurrences of 'text' and 'Text', also starting and/or ending within a word. I want only occurrences of ' Text ' (case sensitive) with a preceding and trailing ' '.

I know the behaviour of LIKE and = with respect to SPACES, so there is no need to explain this again as it has been done elsewhere on this site.


Solution

  • Try this:

    Test data.

    declare @t table (word nvarchar(50))
    
    insert into @t
    values (' text '), (' Text '), ('text '), (' text'), (' other '), (' text in large string'), ('xxxxxtext'),('xxxxxtext '), ('xxxx text') string')
    

    Relevant query.

    select * from @t
    
    where word like '%' + ' text ' + '%'
    

    Returns:

     text 
     Text 
     text in large string