Unicode 是每个字符两个字节。您的 NText 字段是一个 Unicode 字符串。 DataLength() 返回存储字段所需的字节数,Len() 返回字符数。
来自Len():“返回指定字符串表达式的字符数,不包括尾随空格。” DataLength 不排除尾随空格。对于 Unicode 字符串,您可以使用 DataLength( UnicodeStringExpression ) / DataLength( N'#' ) 来获取字符长度。
一般DataLength( Left( Coalesce( StringExpression, '#' ), 1 ) ) 将返回每个字符的字节数,因为Coalesce 返回一个基于data type precedence 的值,其中Unicode 字符串的优先级高于字节字符串类型(char 和varchar)。
declare @Foo as VarChar(10) = 'Foo and ';
declare @Bar as NVarChar(10) = N'Bar and ';
select @Foo as [@Foo],
Len( @Foo ) as [Len (trimmed)], DataLength( @Foo ) as [DataLength (bytes)],
DataLength( Left( Coalesce( @Foo, '#' ), 1 ) ) as BytesPerCharacter,
DataLength( @Foo ) / DataLength( Left( Coalesce( @Foo, '#' ), 1 ) ) as 'Characters';
select @Bar as [@Bar],
Len( @Bar ) as [Len (trimmed)], DataLength( @Bar ) as [DataLength (bytes)],
DataLength( Left( Coalesce( @Bar, '#' ), 1 ) ) as BytesPerCharacter,
DataLength( @Bar ) / DataLength( Left( Coalesce( @Bar, '#' ), 1 ) ) as 'Characters';