SQL char to compare varchar why?

Why does the following return the result when the target column in the where clause is char (20)?

declare @pallettag varchar(20) set @pallettag = '168531' --set @pallettag = @pallettag + SPACE(20 - Len(@pallettag)) select s.ROWID, s.SUBLOTCODE + '*', @pallettag + '*' from IMSUBLOT as s where s.SUBLOTCODE = @pallettag 

s.SUBLOTCODE is defined as char (20), and I expect to get the result only if I uncomment the third line, where I added the necessary spaces.

+4
source share
2 answers

Intermediate spaces are ignored when comparing strings in SQL Server , with the exception of the expressions on the right in LIKE comparisons.

 SELECT CASE WHEN '168531' = '168531 ' THEN 'Y' ELSE 'N' END AS [=], CASE WHEN '168531' LIKE '168531 ' THEN 'Y' ELSE 'N' END AS [Like RHS], CASE WHEN '168531 ' LIKE '168531' THEN 'Y' ELSE 'N' END AS [Like LHS] 

Returns

 = Like RHS Like LHS ---- -------- -------- YNY 
+4
source

VARCHAR (20) means any character length up to and including 20.

0
source

Source: https://habr.com/ru/post/1382750/


All Articles