In T-SQL, why doesn't the statement work for a variable, but works for a literal?

Here is the script:

First script:

declare @a char(10) = 'AA%'
declare @b char(10) = 'AA001'

if @b LIKE @a 
     print 'Equals' 
else 
begin 
     print 'Not equals' 
end

      

It prints:

Not Equals

      

I expected it to print Equals

. But below is the script that does not use @a

in the condition:

Second script:

declare @a char(10) = 'AA%'
declare @b char(10) = 'AA001'

if @b LIKE 'AA%' 
    print 'Equals' 
else 
begin 
    print 'Not equals' 
end

      

prints

Equals

      

So why does the first script consider them not equal, while the second script considers them equal?

+3


source to share


1 answer


The answer is actually simple, but it's a big question: it's because of the type char

.

If we were to print two variables:

print @a
print @b

      



The output would be (dots mean empty space):

AA%.......       
AA001.....   

      

So, the first query does like

for two variables, and trailing spaces make it unequal, because according to

+7


source







All Articles