views:

56

answers:

2

I need to be able to check if a variable has a certain string of text inside it. Here's 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
+2  A: 

dunno...works for me

declare @name varchar(45)

set @name = 'johnson'

IF( @name LIKE '%John%' )
BEGIN
    print 'like'
END
ELSE
BEGIN
    print 'dislike'
END
Jeremy
Aha! My problem was that I declared the variable as a plain varchar, not varchar with a length like you did. Thanks!
I'll mark this as a answer once my account allows me to. (I'm brand new here)
@user322652 - yep, you need to be careful to always give a size. In this scenario, it would default to 1. In other scenarios, the length if not defined would be 30! (I wrote up about this recently here if you're interested: http://www.adathedev.co.uk/2010/04/sql-cast-to-varchar-without-size.html)
AdaTheDev
@user322652: Guess you're able now
abatishchev
you can use `NVARCHAR(MAX)` and it's better always use Nvachar instead of just varchar
abatishchev
@abatishchev - have to disagree with that. If you don't need to store unicode data, then you shouldn't choose NVARCHAR - uses 2 bytes per character instead of 1, which is unneccessary if not needed!
AdaTheDev
@AdaTheDev Thanks.
+1  A: 

The syntax is fine. If it isn't working for you, it could be down to the collation of your database.

If you have a case sensitive collation, then it will NOT match unless the case matches. e.g. if @name is 'Something john said', then a LIKE searching for "John" will not find a match, hence will go to the ELSE.

AdaTheDev
Thanks for that info. I'll vote up your response once I get 15 reputation...
Yeah, it's MS SQL Server. (with all the weirdness that entails) I compared the working version to the non-working version and only found a difference of semicolon line endings on the variable declaration and set and that I didn't define a length for my varchar.