SQL 确定 Nvarchar 长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21259726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:50:32  来源:igfitidea点击:

Determining Nvarchar length

sqlsql-servernvarchar

提问by Kane Jeeves

I've read all about varchar versus nvarchar. But I didn't see an answer to what I think is a simple question. How do you determine the length of your nvarchar column? For varchar it's very simple: my Description, for example, can have 100 characters, so I define varchar(100). Now I'm told we need to internationalize and support any language. Does this mean I need to change my Description column to nvarchar(200), i.e. simply double the length? (And I'm ignoring all the other issues that are involved with internationalization for the moment.)

我已经阅读了有关 varchar 与 nvarchar 的所有信息。但是我没有看到我认为是一个简单问题的答案。如何确定 nvarchar 列的长度?对于 varchar,它非常简单:例如,我的 Description 可以有 100 个字符,因此我定义了 varchar(100)。现在我被告知我们需要国际化并支持任何语言。这是否意味着我需要将我的描述列更改为 nvarchar(200),即只需将长度加倍?(我暂时忽略了与国际化有关的所有其他问题。)

Is it that simple?

有那么简单吗?

回答by Martin Smith

Generally it is the same as for varcharreally. The number is still the maximum number of characters not the data length.

一般来说它和varchar真的一样。该数字仍然是最大字符数而不是数据长度。

nvarchar(100)allows 100 characters (which would potentially consume 200 bytes in SQL Server).

nvarchar(100)允许 100 个字符(这可能会在 SQL Server 中消耗 200 个字节)。

You might want to allow for the fact that different cultures may take more characters to express the same thing though.

您可能希望考虑到这样一个事实,即不同的文化可能需要更多的字符来表达相同的内容。

An exception to this is however is if you are using an SCcollation (which supports supplementary characters). In that case a single character can potentially take up to 4 bytes.

但是,一个例外是如果您使用的是SC排序规则(支持补充字符)。在这种情况下,单个字符可能最多占用 4 个字节。

So worst case would be to double the character value declared.

所以最坏的情况是将声明的字符值加倍。

回答by Zheng Yiong Lai

You can get the answer with a simple experiment, by executing the code below.

通过执行下面的代码,您可以通过一个简单的实验获得答案。

DECLARE @a varchar(4);  SET @a = '123456';  SELECT @a; 
DECLARE @b nvarchar(4);  SET @b = '123456';  SELECT @b;  

They both will return your result '1234' only store 4 characters.

他们都将返回您的结果 '1234' 仅存储 4 个字符。

How do you determine the length of your nvarchar column? Just put the string number of characters you wanted to store in that column.

如何确定 nvarchar 列的长度?只需将您想要存储在该列中的字符串字符数。