2010-07-28 35 views
3

我试图转换一些decimalsvarchar,但他们得到四舍五入为什么这个Sql Server CAST(..)将Decimal舍入到VarChar?

有人能告诉我为什么吗?

declare @UpperLeftLatitude DECIMAL, 
    @UpperLeftLongitude DECIMAL, 
    @BottomRightLatitude DECIMAL, 
    @BottomRightLongitude DECIMAL 

SET @UpperLeftLatitude = 38.663 
SET @UpperLeftLongitude = -122.857 
SET @BottomRightLatitude = 37.795 
SET @BottomRightLongitude = -121.219 


DECLARE @SearchRectangleString VARCHAR(MAX); 
SET @SearchRectangleString = 'POLYGON((' + CONVERT(VARCHAR(50), @UpperLeftLatitude) + ' ' + CAST(@UpperLeftLongitude AS VARCHAR(50)) + ',' 
    + CAST(@BottomRightLatitude AS VARCHAR(50)) + ' ' + CAST(@UpperLeftLongitude AS VARCHAR(50)) + ',' 
    + CAST(@BottomRightLatitude AS VARCHAR(50)) + ' ' + CAST(@BottomRightLongitude AS VARCHAR(50)) + ',' 
    + CAST(@UpperLeftLatitude AS VARCHAR(50)) + ' ' + CAST(@BottomRightLongitude AS VARCHAR(50)) + ',' 
    + CAST(@UpperLeftLatitude AS VARCHAR(50)) + ' ' + CAST(@UpperLeftLongitude AS VARCHAR(50)) + '))'; 

    SELECT @SearchRectangleString 

------------------- 
POLYGON((39 -123,38 -123,38 -121,39 -121,39 -123)) 

(1 row(s) affected) 

注:是的,我知道我的纬度/多头周围走错了路。我会尽快切换。

回答

6

这是因为您的小数未指定长度。他们不存储任何小数位。

尝试以下方法:

DECLARE @test DECIMAL, @test2 DECIMAL(8,4) 
SET @test = 12.3456 
SET @test2 = 12.3456 

SELECT @test, @test2 
+1

远远地抱-发芽。我想在经历了15年的Sql之后,我会选择那个shiz。该回家了。脑中的单个脑细胞非常疲倦。谢了哥们! – 2010-07-28 07:46:40

1

为对照提到它被四舍五入...

当省略或具有0(默认值)一 值函数, 数值_是圆形。当指定了0以外的 值时, 数值表达式被截断。

来源:ROUND (T-SQL)