DECIMAL(3,2)的SQL乘以DECIMAL(18,4)返回DECIMAL(18,4)

时间:2015-08-07 15:53:23

标签: sql sql-server sql-server-2008

我看过很多帖子,人们有类似的问题,但我已经尝试了所有的解决方案,没有一个对我有用。希望你们能指出我的方式的错误..

SQL

SELECT
    --Raw Values
    Hours, --RESULT: 24.0000
    StartStops, --RESULT: 0.0000

    --Equation without CAST/ROUND
    ((Hours * 1.00)) AS "WhatIf Hours", --RESULT: 24.000000
    ((StartStops * 1.00)) AS "WhatIf Starts", --RESULT: 0.000000

    --CAST output of equation
    CAST((Hours * 1.00) as DECIMAL(18,4)) AS "WhatIf Hours", --RESULT: Arithmetic overflow error converting numeric to data type numeric.
    CAST((StartStops * 1.00) as DECIMAL(18,4)) AS "WhatIf Starts", --RESULT: Arithmetic overflow error converting numeric to data type numeric.

    --CAST each input of equation
    CAST(Hours as DECIMAL(18,4)) * CAST(1.00 as decimal(18,4)) AS "WhatIf Hours", --RESULT: 24.00000000
    CAST(StartStops as DECIMAL(18,4)) * CAST(1.00 AS decimal(18,4)) AS "WhatIf Starts", --RESULT: 0.00000000

    --ROUND output of equation
    ROUND((Hours * 1.00), 4) AS "WhatIf Hours", --RESULT: 24.000000
    ROUND((StartStops * 1.00), 4) AS "WhatIf Starts" --RESULT: 0.000000
FROM
   MyTable
WHERE
   ID = 1

所需的结果是算术输出为DECIMAL(18,4),因为这是我将使用该值更新的列类型。可以帮忙吗?

更新:创建表格

CREATE TABLE [dbo].[MyTable](
   [ID] [int] NOT NULL, 
   [Hours] [decimal](18, 4) NULL,
   [StartStops] [decimal](18, 4) NULL,
   [Updated] [datetime] NULL,
   [UpdatedBy] [varchar](50) NULL,  
) ON [PRIMARY]

更新2

这是一张图片,所以你们知道我并不疯狂。

enter image description here

SQLFIDDLE

2 个答案:

答案 0 :(得分:4)

问题可能在您的设置中。请参阅以下示例:

运行:

SET NUMERIC_ROUNDABORT ON declare @num decimal(18,4) = 24.0000 select cast((@num * 1.00) as decimal(18,4))

结果为Arithmetic overflow error converting numeric to data type numeric。但是,运行

SET NUMERIC_ROUNDABORT OFF declare @num decimal(18,4) = 24.0000 select cast((@num * 1.00) as decimal(18,4))

给出24.0000

根据官方MSN文档(https://msdn.microsoft.com/en-us/library/ms188791.aspx),您可以运行以下代码:

DECLARE @NUMERIC_ROUNDABORT VARCHAR(3) = 'OFF'; IF ( (8192 & @@OPTIONS) = 8192 ) SET @NUMERIC_ROUNDABORT = 'ON'; SELECT @NUMERIC_ROUNDABORT AS NUMERIC_ROUNDABORT;

检查系统设置。

答案 1 :(得分:0)

 CAST((ROUND(Hours * 1.00, 4)) as DECIMAL(18,4)) AS "WhatIf Hours"

你得到了算术溢出,因为你试图将带小数点后6位的小数转换成4位小数。首先将它舍入到4位首先应该这样做

你也可以

CAST((CAST(Hours as DECIMAL(18,4)) * CAST(1.00 as DECIMAL(18,4))) as DECIMAL(18,4))