LEN function not including trailing spaces in SQL Server

This is clearly documented by Microsoft in MSDN at http://msdn.microsoft.com/en-us/library/ms190329(SQL.90).aspx, which states LEN “returns the number of characters of the specified string expression, excluding trailing blanks”. It is, however, an easy detail on to miss if you’re not wary.

You need to instead use the DATALENGTH function – see http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx – which “returns the number of bytes used to represent any expression”.

Example:

SELECT 
    ID, 
    TestField, 
    LEN(TestField) As LenOfTestField,           -- Does not include trailing spaces
    DATALENGTH(TestField) As DataLengthOfTestField      -- Shows the true length of data, including trailing spaces.
FROM 
    TestTable

Leave a Comment