tags:

views:

270

answers:

3

Hi All,

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. ie If the value is 3 character length I've to append 7 spaces to it.

Regards

+2  A: 

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()

RaYell
and LEN() does indeed **ALSO** count whitespaces.......
marc_s
LEN(N'testing one two three, nothing but a test') returns 41 characters including whitespace (and DATALENGTH() on that returns 82)
marc_s
@marc_s ... it doesn't count trailing whitespace though. LEN('HELLO'), LEN('HELLO ') and LEN(' HELLO') returns 5, 5 and 10 consecutively. This is documented ("").
Chris J
Those examples were meant to have no leading/trailing whitespace, five spaces after HELLO and five spaces before HELLO. The joys of HTML collapsing whitespace :-)
Chris J
+2  A: 

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

Joe Chung
+1 LEN on a NVARCHAR field returns the number of characters in the string, while DATALENGTH() returns twice that number (since NVARCHAR stores 2 bytes per character)
marc_s
+2  A: 

len counts the number of characters used not the storage required, this will be even more evident when you use nvarchar instead of varchar

len does not count trailing spaces either

take a look at this

declare @v nchar(5)
select @v ='ABC  '


select len(@v),datalength(@v)

and the output for len is 3 while the output for datalength =10

SQLMenace