For fields with generic string types in your program, there are four types of char, varchar, nchar, and nvarchar in SQL Server, so what's the difference between these four types?
1. Fixed-length or variable-length
The so-called fixed-length is long, when the length of the data to be saved will automatically fill in the back of the English space, so that the length of the corresponding length; there is the Var prefix, indicating that the actual storage space is dynamic change, such as Varchar,nvarchar variable length character data will not be filled with space.
2.Unicode or non-Unicode
In a database, English characters require only one byte of storage, but Chinese characters and many other non-English characters require two bytes of storage. If the English and Chinese characters exist simultaneously, due to the number of space occupied, it is easy to create confusion, resulting in the reading of the string is garbled. The Unicode character set is created to resolve incompatible problems with the character set, all of which are represented in two bytes, that is, English characters are also represented in two bytes. The prefix n represents Unicode characters, such as Nchar,nvarchar, which use the Unicode character set.
3. Maximum capacity for storage of several data types
Char,varchar up to 8,000 English, 4,000 Chinese characters
Nchar,nvarchar can store up to 4,000 characters, whether in English or Chinese
Copy Code code as follows:
--Create a table
CREATE TABLE temptable (
ID INT PRIMARY KEY,
Charfield CHAR (10),
Varcharfield VARCHAR (10),
Nvarcharfield NVARCHAR (10)
)
INSERT into TempTable VALUES (1, ' wfth ', ' wfth ', ' wfth ')
INSERT into TempTable VALUES (2, ' no wind listens to the sea ', ' no wind listens to the sea ', ' no wind listens to the sea ')
INSERT into TempTable VALUES (3, ', ', ', ')
INSERT into temptable (ID) VALUES (4)
INSERT into TempTable VALUES (5, ' 1234567890 ', ' 1234567890 ', ' 12345 ')
SELECT datalength (Charfield) as Charfieldlen,
Datalength (Varcharfield) as Varcharfieldlen,
Datalength (Nvarcharfield) as Nvarcharfieldlen
From temptable WHERE ID =1
SELECT datalength (Charfield) as Charfieldlen,
Datalength (Varcharfield) as Varcharfieldlen,
Datalength (Nvarcharfield) as Nvarcharfieldlen
From temptable WHERE ID =2
SELECT datalength (Charfield) as Charfieldlen,
Datalength (Varcharfield) as Varcharfieldlen,
Datalength (Nvarcharfield) as Nvarcharfieldlen
From temptable WHERE ID =3
SELECT datalength (Charfield) as Charfieldlen,
Datalength (Varcharfield) as Varcharfieldlen,
Datalength (Nvarcharfield) as Nvarcharfieldlen
From temptable WHERE ID =4
SELECT datalength (Charfield) as Charfieldlen,charfield,
Datalength (Varcharfield) as Varcharfieldlen,varcharfield,
Datalength (Nvarcharfield) as Nvarcharfieldlen,nvarcharfield
From temptable WHERE ID =5