In SQL Server 2005, what is the difference between len() and datalength()?

送分小仙女□ 提交于 2020-04-13 07:31:37

问题


What is the difference between len() and datalength() in SQL Server 2005?


回答1:


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:

http://msdn.microsoft.com/en-us/library/ms190329.aspx




回答2:


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




回答3:


The 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




回答4:


With regards to strings datalength() returns the number of bytes and len() returns an integer value for the number of characters.



来源:https://stackoverflow.com/questions/558102/in-sql-server-2005-what-is-the-difference-between-len-and-datalength

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!