将int转换为real是有什么限制的

时间:2017-02-10 10:58:30

标签: sql-server tsql casting

当我写:

SELECT CAST (CAST (32652317 as real) as int)

结果是:

32652316

real类型的列中安全存储的最大整数是多少,而不会出现错误值的风险?

1 个答案:

答案 0 :(得分:4)

只是为了好玩:

以下代码将返回第一个数字,其中您的演员表与原始编号不同。

WITH x AS(SELECT 1 AS N FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS tbl(N))--10^1
    ,N3 AS (SELECT 1 AS N FROM x CROSS JOIN x AS N2 CROSS JOIN x N3) --10^3
    ,Tally AS(SELECT (ROW_NUMBER() OVER(ORDER BY(SELECT NULL))) AS Nr FROM N3 
              CROSS JOIN N3 N6 CROSS JOIN N3 AS N9)
SELECT TOP 1 Nr,CAST (CAST (Tally.Nr AS REAL) AS INT)
FROM Tally
WHERE Nr<>CAST (CAST (Tally.Nr AS REAL) AS INT);

我的结果是16777217 and 16777216

更新

数字越大,差异越大。以下查找differenc高于2的第一个:

WITH x AS(SELECT 1 AS N FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS tbl(N))--10^1
    ,N3 AS (SELECT 1 AS N FROM x CROSS JOIN x AS N2 CROSS JOIN x N3) --10^3
    ,Tally AS(SELECT (ROW_NUMBER() OVER(ORDER BY(SELECT NULL))) AS Nr FROM N3 
              CROSS JOIN N3 N6 CROSS JOIN N3 AS N9)
SELECT TOP 1 Nr,CAST (CAST (Tally.Nr AS REAL) AS INT)
FROM Tally
WHERE ABS(Nr-CAST (CAST (Tally.Nr AS REAL) AS INT))>2

我的结果是67,108,867 and 67,108,864

当被问到 >5 时,我得到了134,217,734 and 134,217,728

更新:浮动与真实

如果用REAL替换FLOAT,则不会有任何允许的INT打破你的演员阵容,但这需要8个字节的存储空间。

根据this page REAL被视为FLOAT(24)占用4个字节。 32位中的24位用于尾数。 FLOAT需要INT - 参数来设置其宽度。 FLOAT(24)远低于最大宽度。省略此参数默认值为最大值53,但占用8个字节。

即使FLOAT(1),至少有1位被保留用于尾数。当第7个字节“开始”时,舍入开始。这发生在16777217以下的1个数字:

Byte 7 is begun