我有一个变量,我希望在小数点左边返回最多5个,并且总是在右边3个
CONVERT(VARCHAR(14),CONVERT(DECIMAL(8,3),
DATEDIFF(MILLISECOND,@ProcessTime,GETDATE()))/@OneThousand)
现在变量定义为
DECLARE @ProcessTime DATETIME
DECLARE @OneThousand DECIMAL(8,3)
SET @OneThousand = 1000.000
这总是返回类似
的内容0.003000000000
我想我可以用左功能解决我的问题,但我的问题是为什么会发生这种情况。如果定义的最小小数变量@OneThousand
为3,那么返回值是否应该有3位小数?
答案 0 :(得分:2)
将DECIMAL(8,3)
除以DECIMAL(8,3)
的结果给出了DECIMAL(20,12)
的数据类型以查看此内容
DECLARE @ProcessTime DATETIME =getdate()
DECLARE @OneThousand DECIMAL(8,3)
SET @OneThousand = 1000.000
DECLARE @v SQL_VARIANT
SET @v = CONVERT(DECIMAL(8,3),
DATEDIFF(MILLISECOND,@ProcessTime,GETDATE()))/@OneThousand
SELECT
CAST(SQL_VARIANT_PROPERTY(@v, 'BaseType') AS VARCHAR(30)) AS BaseType,
CAST(SQL_VARIANT_PROPERTY(@v, 'Precision') AS INT) AS Precision,
CAST(SQL_VARIANT_PROPERTY(@v, 'Scale') AS INT) AS Scale
BOL部分解释了decimal(20,12)
is here
Operation: e1 / e2
Result precision: p1 - s1 + s2 + max(6, s1 + p2 + 1)
Result scale: max(6, s1 + p2 + 1)
所以在你的情况下
Result precision: 8 - 3 + 3 + max(6, 3 + 8 + 1) = 20
Result scale: max(6, 3 + 8 + 1) = 12
答案 1 :(得分:1)
...试
SELECT CAST(DATEDIFF(ms, @processDate, GETDATE()) / 1000.000 AS decimal(8,3))