How to use a LIKE statement inside an IF statement?

I need to check if a variable has a specific line of text inside it. Here is what I have now:

--This sample always goes to the ELSE block.
IF( @name LIKE '%John%' )
BEGIN
    --do one thing
END
ELSE
BEGIN
    --do the other thing
END
+3
source share
2 answers

dunno ... works for me

declare @name varchar(45)

set @name = 'johnson'

IF( @name LIKE '%John%' )
BEGIN
    print 'like'
END
ELSE
BEGIN
    print 'dislike'
END
+2
source

The syntax is beautiful. If it does not work for you, it may be due to the sorting of the database.

If you have case-sensitive sorting, then it will NOT match if there is no match. for example, if @name is "Something john said", then the LIKE search for "John" will not find a match, so it will switch to ELSE.

+1
source

Source: https://habr.com/ru/post/1742166/


All Articles