2012-03-30 213 views
0

在sql中的这种评估似乎不能正常工作的原因,但我不明白为什么。SQL数学评估问题

让我们先看看这个例子。

DECLARE @countRatio decimal(6,3)  
SET @countRatio = (((4)/(2))*(6))/100.0 
_______________________________________ 
0,120 

这个评价就像一个魅力。我的计算器也得到了相同的答案。

但这个例子给了我一个意想不到的答案。

DECLARE @countRatio decimal(6,3)  
SET @countRatio = (((2)/(4))*(6))/100.0 
_______________________________________ 
0,000 

当我计算这对我的计算器答案是0,03 这acording对我来说是正确的。但sql一直给我0,000个答案。有任何想法吗?

回答

3

问题是((2)/(4))四舍五入为INT,因为2和4都是INTs。如果改为使用2.0或4.0,你得到正确的结果:

DECLARE @countRatio decimal(6,3)  
SET @countRatio = (((2.0)/(4))*(6))/100.0 
SELECT @countRatio 
========================== 
0.030 

在任何算术表达式,SQL Server将强制转换成具有更高的精度操作的类型。因此2.0/4会将结果转换为2.0的类型,即float

2

24是整数,所以SQL使用整数除法,即给出0。这将工作:

DECLARE @countRatio decimal(6,3)  
SET @countRatio = (((2.0)/(4.0))*(6))/100.0 
0
declare @countRatio decimal(6,3)  

-- Using integers 2/4 = 0: 
set @countRatio = ((2/4) * 6)/100.0 
select @countRatio 

-- Using decimal values 2/4 = 0.5: 
set @countRatio = ((2./4.) * 6.)/100.0 
select @countRatio 

-- Explicitly converting a value to decimal will cause the other values to be promoted to decimal: 
set @countRatio = ((Cast(2 as Decimal)/4) * 6)/100.0 -- Decimals. 
select @countRatio 

-- Or: 
set @countRatio = ((Convert(Decimal, 2)/4) * 6)/100.0 -- Decimals. 
select @countRatio 

-- The promotion occurs when it is needed. Hence this doesn't do what you want: 
set @countRatio = ((2/4) * Convert(Decimal, 6))/100.0 -- Decimals. 
select @countRatio