The difference between the two built-in functions of DataLength() and Len() in SQL Server

I have encountered a problem in my recent work: when declaring the field type in the database, char(4), but only three letters of 'DCE' are actually stored. In the program assembling the Map with this field as the key, the 'DCE'+ Space is used as its Key, so that the value of Value cannot be obtained by using 'DCE' without space as the key, and the result is empty. Later, I looked at the database field type and found the problem. As we all know, the difference between char and varchar is that one is fixed length and the other is variable length. In the process of finding the problem, I used the two built-in functions we are going to talk about today, DataLength() and Len(). Before explaining the difference between DataLength() and Len(), let's first understand the difference between varchar(n) and nvarchar(n). varchar(n): Non-Unicode-encoded character data of length n bytes, where n must be a value between 1 and 8000. The storage size is the actual length in bytes of the input data, not n bytes. nvarchar(n): Variable-length Unicode character data containing n characters, n must be between 1 and 4000, and the storage size in bytes is twice the number of characters entered. That is to say, varchar(2) can store up to 2 letters, or 1 Chinese character; and nvarchar(2) can store up to 2 letters, or two Chinese characters, that is, nvarchar(2) contains two characters = 4 bytes. Knowing the above, let's take a look at the difference between DataLength() and Len() through an example:

  1. --declare a scalar variable  
  2. declare @a varchar(max)  
--declare a scalar variable
declare @a varchar(max)
  1. --Assign the variable 'AAA'  
  2. set @a = 'AAA'  
--Assign the variable 'AAA'
set @a = 'AAA'
  1. -- Query the length separately  
  2. select LEN(@a) AS a_len,DATALENGTH (@a) AS a_datalength  
-- Query the length separately
select LEN(@a) AS a_len,DATALENGTH (@a) AS a_datalength

1. @a='AAA', the result is as follows:

 

2. @a='AAA ', where two spaces are added at the end, the result is as follows:

3. @a='AAA', two spaces are added in front of it, the result is as follows:

4. @a='AA A', where a space is added between each A, the result is as follows:

Concluded as follow:

The difference between DataLength() and Len() when using a non-Unicode encoding, that is, a string of type varchar:

L en() The number of characters in the string expression, not counting trailing spaces, but counting head spaces and middle spaces;

DataLength() The number of bytes of any expression, including spaces.

When using UniCode coding, interested students can try the results by themselves.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325272477&siteId=291194637