Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the T-SQL "LIKE" operator not evaluating this expression like I think it should?

I am attempting to error trap a T-SQL variable name by making sure that the value of the variable is prefixed with a bracket "[".

Here's an example of how I am trying to do this:

DECLARE @thing nvarchar(20)
SET @thing = '[55555'
IF(@thing NOT LIKE '[' + '%') --If the value does not start with [ then add it
BEGIN
SET @thing = '[' + @thing
END
PRINT @thing

The example above PRINT's [[55555

Notice that the original value of @thing was prefixed with the bracket "[". I was expecting the IF condition would have returned false since "[55555" is LIKE '[' + '%'

Why is the IF condition not returning false? And, more importantly I suppose, what is the correct syntax to check for the existence of a string that occurs at the beginning of a variable string value?

EDIT It appears as there is something special about the bracket "[". When I run LIKE on a bracket it doesn't do what I expect, but when I don't use a bracket the LIKE works the way I expect.

Check out these examples:

IF('[' NOT LIKE '[')
BEGIN
PRINT '[ is NOT LIKE ['
END
ELSE
BEGIN
PRINT '[ is LIKE ['
END

IF('StackO' NOT LIKE 'StackO')
BEGIN
PRINT 'STACKO is NOT LIKE StackO'
END
ELSE
BEGIN
PRINT 'STACKO is LIKE StackO'
END

Here's the output of the two conditions:

[ is NOT LIKE [

STACKO is LIKE StackO

like image 305
Jed Avatar asked Jul 22 '11 23:07

Jed


1 Answers

I believe it may be because '[' is actually part of the LIKE operators syntax, as defined here: http://msdn.microsoft.com/en-us/library/ms179859.aspx

You need to define an escape character to escape the [, like this:

DECLARE @thing nvarchar(20)
SET @thing = '[55555'
IF(@thing NOT LIKE '\[%' ESCAPE '\' )
BEGIN
SET @thing = '[' + @thing
END
PRINT @thing

An alternative solution would be the following:

DECLARE @thing nvarchar(20)
SET @thing = '[55555'
IF(LEFT(@thing,1) <> '[') --If the value does not start with [ then add it
BEGIN
SET @thing = '[' + @thing
END
PRINT @thing
like image 150
Tom Studee Avatar answered Sep 28 '22 08:09

Tom Studee