SQL Server 总和更改数据类型

本文关键字:数据类型 Server SQL | 更新日期: 2023-09-27 18:33:04

我正在使用SQL Server 2008总结一些数据。 数据类型为 money,并且设置为不允许空值。 当我总结它时,结果数据是金钱,但允许空值。 当我在 C# 中使用代码时,这是一个问题,因为不允许空值的钱不等于允许空值的钱,以及允许空数据的其他问题。 我能做些什么来解决这个问题?

我的SQL是:

SELECT     
    dbo.Subcontracts.SubcontractID, dbo.Subcontracts.AccountNumber, 
    dbo.SubcontractAmounts.ObjectCode, dbo.Subcontracts.AppendId, 
    dbo.Subcontracts.BeginDate, dbo.Subcontracts.EndDate, 
    dbo.Subcontracts.RecipientGrantorId, dbo.Subcontracts.CheckA133, 
    dbo.Subcontracts.CheckDebarment, dbo.Subcontracts.CostshareRequired, 
    dbo.Subcontracts.CostshareAmountRequired, dbo.Subcontracts.CreatedOn, 
    dbo.Subcontracts.CreatedBy, dbo.Subcontracts.ModifiedOn, 
    dbo.Subcontracts.ModifiedBy, dbo.Subcontracts.IsDeleted, dbo.Subcontracts.FARate, 
    dbo.Subcontracts.SubContractAgreementTypeId, dbo.Subcontracts.ContractRiskLevelId, 
    CAST(SUM(dbo.SubcontractAmounts.SubAmount) AS money) AS TotalSubAmount, 
    SUM(dbo.SubcontractPayments.PaymentAmount) AS TotalPaymentAmount, 
    SUM(dbo.SubcontractPayments.AdvanceAmount) AS TotalAdvanceAmount, 
    SUM(dbo.SubcontractPayments.CostshareAmount) AS TotalCostshareAmount, 
    SUM(dbo.SubcontractAmounts.SubAmount - dbo.SubcontractPayments.PaymentAmount) AS UnpaidBalance
FROM          
    dbo.Subcontracts 
INNER JOIN
    dbo.SubcontractAmounts ON dbo.Subcontracts.SubcontractID = dbo.SubcontractAmounts.SubcontractID 
LEFT OUTER JOIN
    dbo.SubcontractPayments ON dbo.SubcontractAmounts.SubcontractAmountID = dbo.SubcontractPayments.SubcontractAmountID
GROUP BY 
    dbo.Subcontracts.SubcontractID, dbo.Subcontracts.AccountNumber, 
    dbo.Subcontracts.AppendId, dbo.Subcontracts.BeginDate, dbo.Subcontracts.EndDate, 
    dbo.Subcontracts.RecipientGrantorId, dbo.Subcontracts.CostshareAmountRequired, 
    dbo.Subcontracts.CreatedOn, dbo.Subcontracts.CreatedBy, 
    dbo.Subcontracts.ModifiedOn, dbo.Subcontracts.ModifiedBy, dbo.Subcontracts.FARate, 
    dbo.Subcontracts.SubContractAgreementTypeId, dbo.Subcontracts.ContractRiskLevelId, 
    dbo.Subcontracts.IsDeleted, dbo.Subcontracts.CheckA133, dbo.Subcontracts.CheckDebarment, 
    dbo.Subcontracts.CostshareRequired, dbo.SubcontractAmounts.ObjectCode

这被拉入一个名为Subsonic的第三方工具中。这会将数据识别为可空,我不想要。由于生成了与数据交互的代码,因此我不能只是更改它。 我可以在使用它的任何地方将数据更改为不可为空,但这不是一个理想或好的解决方案。

SQL Server 总和更改数据类型

您可以尝试将结果显式转换为非空值:

SELECT ISNULL(SUM(Amount), 0) FROM MyTable

或者在 C# 端处理可能的null值。

使用十进制作为您的货币类型,因为它将始终具有一些默认值。喜欢:

decimal myMoney = 300.5m;

如果需要具有可为 null 的类型十进制,则可以使用 decimal? 。然后你可以做myDecimal.HasValue

如果你对结果为 0 感到满意,否则你会得到一个 null:

long result = (long)(dbCommand.ExecuteScalar() ?? 0)