Home > sqlserver > Len vs. Datalength - Life changing information

Len vs. Datalength - Life changing information

February 24th, 2009

Prepare for your entire world to be rocked.

len returns the number of characters in an expression.

datalength returns the number of bytes in an expression.

So this broke my intuition twice recently:

1. len(' ') (single space) returns 0.
To quote from BOL:

Returns the number of characters, instead of the number of bytes, of the specified string expression, excluding trailing blanks.

So, if the blank character is the only character in the string, is it a trailing blank?  Apparently so.
2. nvarchar will return what you want with len in most cases, but datalength for space allocation exercises.

declare @nData nvarchar(max)

select len(''), datalength('')
select len('1 '), datalength('1 ')
select len(' '), datalength(' ')

set @nData = 'A'
select len(@nData), datalength(@nData)

returns the following:

blank       blank
----------- -----------
0           0

(1 row(s) affected)

charSpace   charSpace
----------- -----------
1           2

(1 row(s) affected)

singleSpace singleSpace
----------- -----------
0           1

(1 row(s) affected)

uSingle              uSingle
-------------------- --------------------
1                    2

(1 row(s) affected)

sqlserver

  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.
?>?>