What is the difference between len() and datalength() in SQL Server 2005?
views:
709answers:
4The Len() will trim (remove trailing spaces) from the data.
The DataLength() function does not
Examples: Select Len('Test ') -- this will return 4
Select DATALENGTH ('Test ') -- this will return 5
FURTHERMORE (aggregated from other fantastic and useful answers):
DATALENGTH returns the length of the string in BYTES, including trailing spaces http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx
LEN returns the length in CHARACTERS, excluding trailing spaces http://msdn.microsoft.com/en-us/library/ms190329.aspx
Since strings might consist of one or 2 bytes (Unicode), the results of using either will vary depending on both the data type of the string AND whether there are trailing spaces in the string
For example,
SELECT LEN('string'), LEN('string '), DATALENGTH('string'), DATALENGTH('string '), LEN(N'string'), LEN(N'string '), DATALENGTH(N'string'), DATALENGTH(N'string ')
Will return 6, 6, 6, 7, 6, 6, 12, 14
DATALENGTH returns the length of the string in bytes, including trailing spaces. LEN returns the length in characters, excluding trailing spaces. For example,
SELECT LEN('string'), LEN('string '), DATALENGTH('string'), DATALENGTH('string '), LEN(N'string'), LEN(N'string '), DATALENGTH(N'string'), DATALENGTH(N'string ')
will return 6, 6, 6, 9, 6, 6, 12, 18
With regards to strings datalength() returns the number of bytes and len() returns an integer value for the number of characters.
DATALEN will return the number of bytes that are used to store the value:
http://msdn.microsoft.com/en-us/library/ms173486(SQL.90).aspx
LEN will return the number of characters in a string. Since a string can use single or double-byte characters, this differs from DATALENGTH in that you will always get 1, no matter how long a single character is: