刚刚遇到一个有趣的:
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在过去,这似乎不是一个不寻常的决定。
有趣的是,根据我找到的文档,只有转换为整数会导致截断,其他会导致舍入。尽管出于某些奇怪的原因,从 money
到 integer
的转换似乎与趋势相反,因为它允许四舍五入。
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/