为什么SQL Len函数会为此查询返回7?

时间:2016-11-04 22:45:51

标签: sql sql-server tsql

对于此TSQL查询:

SELECT CAST(116.33 / 8 AS FLOAT) AS [Float Value]
 , LEN(CAST(116.33 / 8 AS FLOAT)) AS [Length of Float Value]
 , LEN(CAST(CAST(116.33 / 8 AS FLOAT) AS VARCHAR)) AS [Length Cast As Varchar]

结果:

Float Value  | Length of Float Value  |  Length Cast As Varchar
14.54125     | 7                      |  7

当我转换为Varchar时,为什么LEN会产生7而不是8?另外,隐式转换或转换会为LEN产生8?

3 个答案:

答案 0 :(得分:2)

Len function on Float in SQLServer gives wrong length非常相关,@ rbr94的答案很好地解释了这一点:

  

LEN()适用于[N] VARCHAR(),因此您正在进行从FLOAT到VARCHAR的隐式转换

通过扩展您的查询可以轻松证明:

SELECT CAST(116.33 / 8 AS FLOAT) AS [Float Value]
 , LEN(CAST(116.33 / 8 AS FLOAT)) AS [Length of Float Value]
 , LEN(CAST(CAST(116.33 / 8 AS FLOAT) AS VARCHAR)) AS [Length Cast As Varchar]
 , CAST(CAST(116.33 / 8 AS FLOAT) AS VARCHAR) AS [Cast As Varchar]

给出了

Float Value Length of Float Value   Length Cast As Varchar  Cast As Varchar
14.54125    7                       7                       14.5413

答案 1 :(得分:0)

如果我错了,请纠正我,但浮标的标准精度是7,因此这可能是你的问题。

首先将结果转换为float,结果为7位数。

请查看此微软post

答案 2 :(得分:0)