nvarchar是什么意思?
SQL Server中的char、nchar、varchar和nvarchar有什么区别?
nvarchar是什么意思?
SQL Server中的char、nchar、varchar和nvarchar有什么区别?
当前回答
Nchar是固定长度的,可以保存unicode字符。每个字符使用两个字节的存储空间。 Varchar是可变长度的,不能保存unicode字符。它使用一个字节存储每个字符。
其他回答
区别在于:
N [var]char存储unicode,而[var]char仅存储单字节字符。 [n]char需要固定长度的字符数,而[n]varchar接受可变长度的字符数,直到并包括定义的长度。
另一个区别是长度。nchar和nvarchar的长度都可以达到4000个字符。char和varchar最多可以有8000个字符长。但是对于SQL Server,你也可以使用[n]varchar(max),它最多可以处理2147,483,648个字符。(2g,一个有符号的4字节整数。)
Nchar是固定长度的,可以保存unicode字符。每个字符使用两个字节的存储空间。 Varchar是可变长度的,不能保存unicode字符。它使用一个字节存储每个字符。
到目前为止,所有的答案都表明varchar是单字节,nvarchar是双字节。第一部分实际上取决于如下所示的排序方式。
DECLARE @T TABLE
(
C1 VARCHAR(20) COLLATE Chinese_Traditional_Stroke_Order_100_CS_AS_KS_WS,
C2 NVARCHAR(20)COLLATE Chinese_Traditional_Stroke_Order_100_CS_AS_KS_WS
)
INSERT INTO @T
VALUES (N'中华人民共和国',N'中华人民共和国'),
(N'abc',N'abc');
SELECT C1,
C2,
LEN(C1) AS [LEN(C1)],
DATALENGTH(C1) AS [DATALENGTH(C1)],
LEN(C2) AS [LEN(C2)],
DATALENGTH(C2) AS [DATALENGTH(C2)]
FROM @T
返回
请注意,VARCHAR版本中仍然没有表示华和国字符,它们被无声地替换为?。
在这种排序中,实际上仍然没有可以用一个字节表示的汉字。唯一的单字节字符是典型的西方ASCII字符集。
正因为如此,从nvarchar(X)列到varchar(X)列的插入可能会因截断错误而失败(其中X表示两个实例中相同的数字)。
SQL Server 2012增加了支持UTF-16的SC(补充字符)排序规则。在这些排序中,单个nvarchar字符可能占用2或4个字节。
我试图总结和纠正现有的答案:
首先,char和nchar将总是使用固定数量的存储空间,即使要存储的字符串小于可用空间,而varchar和nvarchar将只使用存储该字符串所需的存储空间(加上两个字节的开销,假定用于存储字符串长度)。记住,var的意思是变量,就像在变量空间里一样。
The second major point to understand is that, nchar and nvarchar store strings using exactly two bytes per character, whereas char and varchar use an encoding determined by the collation code page, which will usually be exactly one byte per character (though there are exceptions, see below). By using two bytes per character, a very wide range of characters can be stored, so the basic thing to remember here is that nchar and nvarchar tend to be a much better choice when you want internationalization support, which you probably do.
现在来看一些细节。
First, nchar and nvarchar columns always store data using UCS-2. This means that exactly two bytes per character will be used, and any Unicode character in the Basic Multilingual Plane (BMP) can be stored by an nchar or nvarchar field. However, it is not the case that any Unicode character can be stored. For example, according to Wikipedia, the code points for Egyptian hieroglyphs fall outside of the BMP. There are, therefore, Unicode strings that can be represented in UTF-8 and other true Unicode encodings that cannot be stored in a SQL Server nchar or nvarchar field, and strings written in Egyptian hieroglyphs would be among them. Fortunately your users probably don't write in that script, but it's something to keep in mind!
另一个令人困惑但有趣的观点是,如果排序代码页要求的话,char和varchar字段可能会为每个字符使用两个字节。(Martin Smith给出了一个很好的例子,他展示了Chinese_Traditional_Stroke_Order_100_CS_AS_KS_WS如何展示这种行为。看看吧。)
更新:从SQL Server 2012开始,终于有了UTF-16的代码页,例如Latin1_General_100_CI_AS_SC,它可以真正覆盖整个Unicode范围。
NVARCHAR可以存储Unicode字符,每个字符占用2字节。