Recently I faced a issue when using len()
in a query to find out the length of a query, len()
was not counting the trailing spaces in the value. Bu
Unfortunately there is no perfect solution that I am aware of.
One of the proposed solutions, LEN(string + '.')-1
returns wrong results (-1) if the string is Unicode of size 4000 or non-Unicode and of size 8000. That is because the concatenation is ignored. You can overcome this if you want, by casting the string to a MAX-size string: LEN(CAST(string as nvarchar(max)) + '.')-1
, but is it worth it?
As mentioned by others, DATALENGTH(string)
returns the number of bytes used for storage. For Unicode strings, it may not be enough to divide the result by 2: Unicode surrogate characters can take more than 16 bits.
All in all, be mindful of the limitations of each approach and choose whatever you believe will cause you less issues.