我使用SQL Server 2008对一些数据进行求和。数据类型为money,并且设置为不允许空值。当我总结时,结果数据是钱,但允许空值。当我在C#中使用代码时,这是一个问题,因为钱不允许空值不等于允许空值的货币,以及null允许数据的其他问题。我能做些什么来解决这个烂摊子?
我的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的第三方工具。这可以将数据视为可以为空的,我不想要。由于生成了与数据交互的代码,因此我无法对其进行更改。我可以在任何地方将数据更改为不可为空,但这不是一个理想的解决方案。
答案 0 :(得分:1)
您可以尝试将结果显式转换为非空值:
SELECT ISNULL(SUM(Amount), 0) FROM MyTable
或者在C#端处理可能的null
值。
答案 1 :(得分:0)
使用decimal作为您的资金类型,因为它总是有一些默认值。像:
decimal myMoney = 300.5m;
如果您需要具有可为空的十进制类型,则可以使用decimal?
。然后你可以myDecimal.HasValue
答案 2 :(得分:0)
如果您对结果为0感到满意,否则您将获得null:
long result = (long)(dbCommand.ExecuteScalar() ?? 0)