SQL 计算 nvarchar 列中的字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14255236/
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 13:05:07  来源:igfitidea点击:

count number of characters in nvarchar column

sqlsql-server-2008datalength

提问by Sam

Does anyone know a good way to count characters in a text (nvarchar) column in Sql Server? The values there can be text, symbols and/or numbers.

有谁知道在 Sql Server 中的文本 (nvarchar) 列中计算字符的好方法吗?那里的值可以是文本、符号和/或数字。

So far I used sum(datalength(column))/2but this only works for text. (it's a method based on datalength and this can vary from a type to another).

到目前为止,我使用过,sum(datalength(column))/2但这仅适用于文本。(这是一种基于数据长度的方法,这可能因类型而异)。

回答by TechDo

You can find the number of characters using system function LEN. i.e.

您可以使用系统函数找到字符数LEN。IE

SELECT LEN(Column) FROM TABLE

回答by Marc

Use

SELECT length(yourfield) FROM table;

回答by Oded

Use the LENfunction:

使用LEN函数:

Returns the number of characters of the specified string expression, excluding trailing blanks.

返回指定字符串表达式的字符数,不包括尾随空格。

回答by brykneval

Doesn't SELECT LEN(column_name)work?

不起作用SELECT LEN(column_name)

回答by mr_eclair

text doesn't work with len function.

text 不适用于 len 函数。

ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types.

ntext、text 和 image 数据类型将在 Microsoft SQL Server 的未来版本中删除。避免在新的开发工作中使用这些数据类型,并计划修改当前使用它们的应用程序。请改用 nvarchar(max)、varchar(max) 和 varbinary(max)。有关更多信息,请参阅使用大值数据类型。

Source

来源

回答by ORSJess

I had a similar problem recently, and here's what I did:

我最近遇到了类似的问题,这就是我所做的:

    SELECT
         columnname as 'Original_Value',
         LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
         N'['+columnname+']' as 'UnicodeStr_Value',
         LEN(N'['+columnname+']')-2 as 'True_Char_Count'
    FROM mytable 

The first two columns look at the original value and count the characters (minus leading/trailing spaces).

前两列查看原始值并计算字符数(减去前导/尾随空格)。

I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.

我需要将它与真实的字符数进行比较,这就是我使用第二个 LEN 函数的原因。它将列值设置为一个字符串,将该字符串强制为 Unicode,然后对字符进行计数。

By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.

通过使用方括号,您可以确保任何前导或尾随空格也算作字符;当然,你不想计算括号本身,所以你在最后减去 2。