Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Len() vs datalength() in SQL Server 2005

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. But datalength() is counting the trailing spaces also.

Does this means that if I'm doing some operation which deals with the actual length of the value then I have to use dalalength() over len().

ex: If I need the value of a particular value to be is of 10 character length. i.e. If the value is 3 character length I've to append 7 spaces to it.

like image 646
Arun P Johny Avatar asked Jul 20 '09 04:07

Arun P Johny


People also ask

What is the difference between Len () and Datalength function?

The LEN function removes trailing spaces not leading spaces. DATALENG function returns the number of bytes occupy in a variable. It also considered the spaces also.

What is Datalength in SQL Server?

The DATALENGTH() function returns the number of bytes used to represent an expression. Note: The DATALENGTH() function counts both leading and trailing spaces when calculating the length of the expression.

Is Len and length is same in SQL?

SQL Server LEN() FunctionThe LEN() function returns the length of a string. Note: Trailing spaces at the end of the string is not included when calculating the length. However, leading spaces at the start of the string is included when calculating the length. Tip: Also look at the DATALENGTH() function.

Does Len in SQL count spaces?

The LEN function does count spaces at the start of the string when calculating the length of the string. The LEN function will return NULL, if the string is NULL.


2 Answers

Be careful. DATALENGTH returns the number of bytes used, not the number of characters.

like image 189
Joe Chung Avatar answered Sep 22 '22 02:09

Joe Chung


Yes that's exactly what you must do. If you want to just get number of characters excluding blanks you would use LEN() function, while in all other cases DATALENGTH().

Even LEN() documentation has an information that to get number of bytes to represent the extension you should use DATALENGTH()

Here are the links to MSDN docs:

LEN()

DATALENGTH()

like image 35
RaYell Avatar answered Sep 19 '22 02:09

RaYell