Difference between datalength () and Len () in SQL Server

Source: Internet
Author: User
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!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.