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
'[%'
and not the form with concatenation? – Rebbecarebbecca