gpt4 book ai didi

sql-server - 隐式转换和舍入

转载 作者:行者123 更新时间:2023-12-03 16:27:28 25 4
gpt4 key购买 nike

刚刚遇到一个有趣的:

declare @test as int
set @test = 47

select @test * 4.333

返回 203.651

declare @test as int
set @test = 47

declare @out as int
set @out = (select @test * 4.333)

select @out

返回 203

declare @test as int
set @test = 47

declare @out as int
set @out = round((select @test * 4.333),0)

select @out

返回 204

现在我知道为什么它这样做了。这是因为存在从 decimal 到 int 的隐式转换,因此需要切掉小数位(因此为 203),而如果我在隐式转换之前四舍五入,我会得到 204。

我的问题是为什么当 SQL Server 进行隐式转换时它不也四舍五入?我知道如果我有一个大数字,它需要存储在一个小地方,我的第一件事是d 做的是对其进行四舍五入,使其尽可能接近原始数字。

这对我来说似乎并不直观。

最佳答案

这让我开始阅读,答案似乎明显不令人满意,我在4.4.1 数字特征部分找到的最早的 SQL 引用(ANSI 92 可用 here)指出

Whenever an exact or approximate numeric value is assigned to a data item or parameter representing an exact numeric value, an approximation of its value that preserves leading significant digits after rounding or truncating is represented in the data type of the target. The value is converted to have the precision and scale of the target. The choice of whether to truncate or round is implementation-defined.

这由 Microsoft 决定,他们选择为 T-SQL 实现两者中的哪一个,为了简单起见,我假设他们选择了截断。来自wikipedia article on rounding在过去,这似乎不是一个不寻常的决定。

有趣的是,根据我找到的文档,只有转换为整数会导致截断,其他会导致舍入。尽管出于某些奇怪的原因,从 moneyinteger 的转换似乎与趋势相反,因为它允许四舍五入。

From     To       Behaviour

numeric numeric Round

numeric int Truncate

numeric money Round

money int Round

money numeric Round

float int Truncate

float numeric Round

float datetime Round

datetime int Round

表格来自 here .

关于sql-server - 隐式转换和舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4441531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com