A nonvarying character column C1 pads out the string with spaces if the string being stored is less than the maximum number of characters the column can store. Thus when the following statement inserts a row, its C1 string contains 80 characters, out which 74 are space characters.
CREATE TABLE MyTable
(
C1 char(80)
);
INSERT INTO MyTable (C1)
VALUES (' ABC');
a)
LEN() returns the number of characters of the specified string
expression, excluding trailing blanks.
I realize those 74 extra spaces were added by database system and not by user, but the fact still remains that string does contain those spaces, so wouldn’t it make more sense for LEN() to also include extra spaces in the result?
b) It appears MS Sql server doesn’t display those 74 extra spaces in the query results window. Why is that?
c) Anyways, I assume when we retrieve this row from a DB, C1 string will contain all those extra spaces?
Thank you
a) That is just how
LENis defined to work, useDATALENGTHto get the length including trailing spaces (but divide by 2 to get the length in characters for unicode datatypes).Trailing space is also ignored in SQL Server for equality comparisons. i.e.
SELECT *will return results.FROM MyTable WHERE C1 = ' ABC'
b) In SSMS it is not very apparent that the trailing spaces are in fact returned, in results to grid mode the column width does not indicate this but if you copy and paste
C1elsewhere you will see the trailing spaces are in fact preserved.One way of seeing this would be to use
DBCC OUTPUTBUFFERAn extract from the results for me is below
All the spaces can be seen following the
ABCc) Yes. See (b)