根据MSDN,VARCHAR数据类型的存储大小是输入数据的实际长度+ 2个字节。我试图理解为什么当我运行这个查询时:
DECLARE @VARCHAR VARCHAR(40) = 'RACING CLUB DE AVELLANEDA'
SELECT DATALENGTH(@VARCHAR) AS Bytes, LEN(@VARCHAR) AS Characters;
@VARCHAR的存储大小与CHAR数据类型相同,它是25而不是27(25 + 2)。
是否与DATALENGTH功能有关?
答案 0 :(得分:5)
datalength将告诉您数据的字节数,它不包括存储中该数据之前的2个字节。 varchar的2字节开销用于记录字符串中的字节数 - 即在您的情况下为25
答案 1 :(得分:4)
DATALENGTH
会返回bytes used
LEN
会返回characters used
只是比较这些结果
DECLARE @VARCHAR VARCHAR(40) = 'RACING CLUB DE AVELLANEDA'
SELECT DATALENGTH(@VARCHAR) AS Bytes, LEN(@VARCHAR) AS Characters;
Bytes: 25 ==> As it is a variable length, returns 25
Characters: 25
DECLARE @VARCHAR CHAR(40) = 'RACING CLUB DE AVELLANEDA'
SELECT DATALENGTH(@VARCHAR) AS Bytes, LEN(@VARCHAR) AS Characters;
Bytes: 40 ==> As it is a fixed length, returns 40
Characters: 25
DECLARE @VARCHAR NVARCHAR(40) = 'RACING CLUB DE AVELLANEDA'
SELECT DATALENGTH(@VARCHAR) AS Bytes, LEN(@VARCHAR) AS Characters;
Bytes: 50 ==> As it is a variable length, returns 25*2 = 50
Characters: 25
DECLARE @VARCHAR NCHAR(40) = 'RACING CLUB DE AVELLANEDA'
SELECT DATALENGTH(@VARCHAR) AS Bytes, LEN(@VARCHAR) AS Characters;
Bytes: 80 ==> As it is a fixed length, returns 40*2 = 80
Characters: 25
您也可以轻松地将+2
添加到DATALENGTH
数据类型的VARCHAR
DECLARE @VARCHAR VARCHAR(40) = 'RACING CLUB DE AVELLANEDA'
SELECT DATALENGTH(@VARCHAR) AS Bytes
,LEN(@VARCHAR) AS Characters
,DATALENGTH(@VARCHAR) + 2 AS ActualUsedBytes
输出
Bytes Characters ActualUsedBytes
25 25 27