Get the App
SLTechnology News&Howtos  ›  Database  › 

A pit in sql server-the difference between len and datalength

Shulou Source: shulou.com Published: 2022-06-01 04:49:10 10月03日 Update

When dealing with problems today, when counting the maximum number of bytes in a field, there was a problem:

select max(len(subject_name)) from dbtabletest;

But the return value is 129.

However, there is always an error on the oracle side, saying that the number of inserted characters is too large, which is really strange.

After a while, I copied the subject_name and found too many spaces behind a line of values in the text editor. Until now, I didn't know that I needed to use datalength to count the spaces at the end. I was really cheated by sql server again.

Fortunately, he finally found the problem!

When using non-Unicode encoding, i.e. varchar type string, DataLength() and Len() are different:

1. Space processing

Len() The number of characters in a string expression, excluding trailing spaces, but counting leading and middle spaces;

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

2. Processing of Chinese characters

The difference is that Len only returns the number of characters, and a Chinese character represents a character. Datalength returns the number of bytes, two bytes for a Chinese character.

Tags: Spaces characters bytes questions Chinese characters processing strings expressions statistics maximum one line two representatives headers exotic fields trails copies text types Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker Shulou Information Xiaomi Apple