Len() vs datalength() in SQL Server 2005

前端 未结 6 904
失恋的感觉
失恋的感觉 2020-12-08 19:36

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

6条回答
  •  时光取名叫无心
    2020-12-08 20:02

    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.

提交回复
热议问题