Code
Declare @ Nvarchar ( 20 ),
@ B Nvarchar ( 20 ),
@ C Nvarchar ( 20 )
Set @ = ' ABC '
Set @ B = ' ABC '
Set @ C = ' ABC '
Select Len ( @ ) As [ Len ] , Datalength ( @ ) As [ Datalength ] -- 3, 6
Select Len ( @ B ) As [ Len ] , Datalength ( @ B ) As [ Datalength ] -- 4,8
Select Len ( @ C ) As [ Len ] , Datalength ( @ C ) As [ Datalength ] -- 3, 8
Len () returns the number of characters in the specified string expression, excluding trailing spaces.
Datalength () returns the number of bytes used to represent any expression.
However, I also found the following problems:
Code
Declare @ D Varchar ( 20 ), -- Variable Length, non-UNICODE character data.
NThe value range is 1 to 8,000.
MaxIndicates that the maximum storage size is 2 ^ 31-1 bytes. The storage size is the actual length of the input data plus two bytes. The length of the input data can be 0 characters
@ E Nchar ( 20 ),--
NCharacters in length.
NThe value must be between 1 and 4,000 (inclusive ). Twice the storage size
NBytes.
@ F Char ( 20 ) -- Fixed length, non-UNICODE character data, length is
N Bytes.
N The value range is 1 to 8,000. The storage size is
N Bytes
Set @ D = ' ABC '
Set @ E = ' ABC '
Set @ F = ' ABC '
Select Len ( @ D ) As [ Len ] , Datalength ( @ D ) As [ Datalength ] -- 3, 3
Select Len ( @ E ) As [ Len ] , Datalength ( @ E ) As [ Datalength ] -- 3, 40
Select Len ( @ F ) As [ Len ] , Datalength ( @ F ) As [ Datalength ] -- 3, 20
I am confused about the results returned by datalength for these three types. Please kindly advise. Thank you!