Description of LEN() function on MSDN : Returns the number of characters of the specified string expression, excluding trailing blanks.
Why was the LEN() function designed to work this way? What problem does this behaviour solve?
Related :
It fixes the automatic padding of strings due to the data type length. Consider the following:
DECLARE @Test CHAR(10), @Test2 CHAR(10)
SET @Test = 'test'
SET @Test2 = 'Test2'
SELECT LEN(@Test), LEN(@Test + '_') - 1, LEN(@Test2), LEN(@Test2 + '_') - 1
This will return 4, 10, 5 and 10 respectively. Even though no trailing spaces were used for @Test, it still maintains its length of 10. If LEN did not trim the trailing spaces then LEN(@test)
and LEN(@Test2)
would be the same. More often than not people will want to know the length of the meaningful data, and not the length of the automatic padding so LEN removes trailing blanks. There are workarounds/alternatives where this is not the required behaviour.
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