为什么这个Sql Server CAST(..)将十进制舍入为VarChar?

时间:2010-07-28 07:37:21

标签: sql-server sql-server-2008 casting rounding-error

我正在尝试将某些decimals转换为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)

注意:是的,我知道我的Lat / Longs是错误的方式。我很快就会换掉它。

2 个答案:

答案 0 :(得分:6)

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

尝试以下方法:

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

 SELECT @test, @test2

答案 1 :(得分:1)

正如ck所提到的那样,它变得圆滑......

  

省略功能或有功能时   值为0(默认值),   numeric_expression是舍入。当一个   指定了0以外的值,   numeric_expression被截断。

来源:ROUND (T-SQL)