2013-04-08 123 views
1

我需要你的幫助:SUM函數不返回小數

我想要得到的金額字段的總和,它包含十進制值,但我得到的只是INTEGER一部分,我需要DECIMAL太:

DECLARE @TOTAL AS DECIMAL(13,2) 

SET @Total = (SELECT SUM(Amount) 
       FROM t_DownPmtTrans 
       WHERE MortgageID = @MortgageID 
       AND DatePaid IS NULL 
       AND SchedPayment IS NOT NULL) 

我試圖用遊標,但我得到相同的:

OPEN dpt_cursor 
SET @Total= 0.0 

FETCH NEXT FROM dpt_cursor INTO @DownPmtTransID, @Amount 

WHILE @@FETCH_STATUS= 0 
BEGIN 

    PRINT @Amount 
    SET @Total = (@Total + @Amount) 

    FETCH NEXT FROM dpt_cursor 
    INTO @DownPmtTransID, @Amount 
END 

RETURN @Total* (-1) 
CLOSE dpt_cursor 
DEALLOCATE dpt_cursor 

謝謝!

+5

當你聲明@Total,什麼樣的數據類型是它的價值? – Melanie 2013-04-08 18:12:17

+2

您使用的是什麼DBMS? Plelase編輯你的問題,並用你的實現的特定標籤替換sql標籤。 – Barmar 2013-04-08 18:12:48

+1

@Barmar'@@ FETCH_STATUS'表示SQL Server。 – Kermit 2013-04-08 18:13:54

回答

1

我也無法複製,但是在任何情況下,將您正在彙總到變量的數據類型的列轉換應該會得到您想要的結果。這不會是這種情況的唯一原因是,如果「數量」是一個int ...

DECLARE @TOTAL AS DECIMAL(13,2) 

SET  @Total = (SELECT SUM(Convert(DECIMAL(13,2),Amount)) 
        FROM t_DownPmtTrans 
        WHERE MortgageID = @MortgageID 
        AND  DatePaid IS NULL 
        AND  SchedPayment IS NOT NULL) 

由於問題SQL之外我做了快速搜索,發現這一點:http://forums.asp.net/t/33723.aspx/1

根據對此,這是一個已知的問題。我環視了一下,雖然這傢伙沒有說這有幫助,我會建議創建一個SqlParameter對象,以便您可以設置該對象的精度屬性,然後將其傳遞給您的添加方法。

+0

感謝大家,問題出在我的.NET代碼中,仍然不知道爲什麼。我得到一個整數,但如果我直接在數據庫中查詢我得到一個十進制。 代碼IM實現: – 2013-04-08 18:55:46

+0

這是我的代碼: 嘗試 conexion.Open() cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add( 「@ Auth_Reference」,SqlDbType.VarChar).value的= authReference 暗淡RETVAL作爲新的SqlParameter( 「@共」,SqlDbType.Decimal,10) retval.Direction = ParameterDirection.ReturnValue cmd.Parameters.Add(RETVAL) cmd.ExecuteNonQuery() 嘗試 totalSchedPayments =(cmd.Parameters.Item (「@Total」)Value) Catch ex As Exception End Try Catch ex As SqlException – 2013-04-08 18:56:31

+0

@EmmanuelSantana我添加了一些額外的信息。我認爲問題是你傳遞給SqlParameterCollection的SqlParameter對象沒有定義精度,所以它默認爲零,並且舍入爲int。 – 2013-04-08 19:15:27

2

根據MSDN,如果表達式爲decimalsum將返回decimal(38, s)。確保數據類型爲amountdecimal。或者嘗試使用castconvert將其轉換爲decimal。這個選項可以幫助你。

2

您需要設置精度和擴展,而不是尺寸 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.scale(v=vs.100).aspx

var outputParameter = new SqlParameter 
{ 
    Direction = ParameterDirection.Output, 
    ParameterName = "your parameter name in your stored procedure", 
    SqlDbType = SqlDbType.Decimal, 
    Precision = 13, 
    Scale = 2 
}; 

聲明的SQL參數數組和參數添加到它

var parameters = new SqlParameter[1]; 
parameters[0] = outputParameter 

聲明一個命令對象

var command = new SqlCommand(); //don't forget everything else 
command.CommandType = CommandType.StoredProcedure; 
command.CommandText = "stored procedure name" 
command.Parameters.AddRange (parameters); 

執行您的命令

command.ExecuteNonQuery(); 

現在讀取參數集合

var value = (decimal) command.Parameters[0].Value;