Why does the following return a result when the target column in the where clause is a 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 would expect to get a result only if I uncomment the third line where I added the needed spaces.
CHAR takes up 1 byte per character. So, a CHAR(100) field (or variable) takes up 100 bytes on disk, regardless of the string it holds. VARCHAR is a variable length string data type, so it holds only the characters you assign to it. VARCHAR takes up 1 byte per character, + 2 bytes to hold length information.
Because of the fixed field lengths, data is pulled straight from the column without doing any data manipulation and index lookups against varchar are slower than that of char fields. CHAR is better than VARCHAR performance wise, however, it takes unnecessary memory space when the data does not have a fixed-length.
In SQL Server a string comparison is done in alphabetical order. That is "allan" is greater than "alan" because alphabetically "alan" comes before "allan". So, numbers are treated the same when doing string comparison, they are treated in alphabetical order...so, '2' is greater than '12'...
Trailing spaces are ignored in string comparisons in SQL Server except for expressions on the right in a LIKE
comparison.
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
---- -------- --------
Y N Y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With