DATALENGTH() 适用于文字但不适用于变量

DATALENGTH() works on literals but doesn't work on variables

select datalength(cast('12345' as nvarchar))查询returns10(这个没问题),但是

declare @string as nvarchar
set @string = cast('12345' as nvarchar)
select datalength(@string)

returns 2 而不是 10。为什么?如何使用 DATALENGHT() 确定存储在变量中的字符串的数据长度?

始终指定字符数据的长度n。例如

declare @string as nvarchar(30)
set @string = cast('12345' as nvarchar(30))
select datalength(@string)

文档中描述了您不这样做时的行为:

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

nchar and nvarchar