I have following code and it returns false for "@B LIKE @A" comparison in last statement.
I want to know that why Like is behaving in this way because as per my knowledge Like does the comparison on based of text not based upon data type.
DECLARE @Var1 Char(20)
DECLARE @Var2 VarChar(20)
SET @Var1 = 'X'
SET @Var2 = 'X'
SELECT
@Var1 AS A,
@Var2 AS B,
LEN(@Var1) AS 'A Length',
LEN(@Var2) AS 'B Length',
CASE WHEN @Var1 = @Var2 THEN 'Yes' ELSE 'No' END AS 'A = B',
CASE WHEN @Var1 LIKE @Var2 THEN 'Yes' ELSE 'No' END AS 'A LIKE B',
CASE WHEN @Var2 LIKE @Var1 THEN 'Yes' ELSE 'No' END AS 'B LIKE A'
@A is of type CHAR(20), so it’s value is padded on the right with spaces to fill it out to a length of 20.
The Len() function excludes trailing spaces, so both @A and @B show a length of 1 even though @A has been padded out with spaces.
For comparisons, SQL Server follows ansi standards which require padding of strings to the same length before comparing, so @A and @B show as equal.
The one exception to this is the LIKE predicate, which does not pad the strings to the same length if the trailing spaces are on the right.
Ref: How SQL Server Compares Strings with Trailing Spaces