In SQL Server 2005, what is the difference between

2019-06-27 06:54发布

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

4条回答
混吃等死
2楼-- · 2019-06-27 07:25

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

查看更多
小情绪 Triste *
3楼-- · 2019-06-27 07:35

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

查看更多
太酷不给撩
4楼-- · 2019-06-27 07:36

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

查看更多
\"骚年 ilove
5楼-- · 2019-06-27 07:37

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

查看更多
登录 后发表回答