2011-04-29 55 views
1

我有我想要的5最大返回小數點左邊始終3的可變權Sql Server的顯著數字

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位小數?

回答

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 
+0

錯誤---我只是改變了我的括號所以它現在INT /十進制(8,3),然後轉換卻又並不解釋什麼,我一直認爲,INT /什麼是詮釋?或爲什麼十進制(20,12)爲上述。 – Mike 2011-04-29 19:54:08

+0

感謝您的解釋。 – Mike 2011-04-29 19:54:53

1

嘗試...

SELECT CAST(DATEDIFF(ms, @processDate, GETDATE())/1000.000 AS decimal(8,3))