2

我想保护以下语句免受被零除错误的影响。我怎样才能做到这一点?

SELECT [MyColumn] = sum( 
   case when v.Process_FundingDt 
   between @begDt and @endDt  
   and v.Loan_Purpose_Desc = 'PURCHASE' 
   then v.Loan_LoanAmt 
   else 0 
   end
 ) / sum (
   case when v.Process_FundingDt 
   between @begDt and @endDt 
   then v.Loan_LoanAmt else 0 
   end
 )
4

2 回答 2

2

这可能会有所帮助:

select [MyColumn] = case when Denominator = 0 then NULL else Numerator / Denominator end
  from (
   select sum( 
   case when v.Process_FundingDt between @begDt and @endDt and v.Loan_Purpose_Desc = 'PURCHASE' then v.Loan_LoanAmt 
     else 0 end ) as Numerator,
   sum (
   case when v.Process_FundingDt between @begDt and @endDt then v.Loan_LoanAmt
     else 0 end ) as Denominator
   ) as Edgar

添加缺少的FROM子句可能会更好。

当然,它可能会与功能发生冲突,具体取决于查询优化器的功能。

于 2013-04-30T00:05:06.247 回答
0

您可以使用此处提到的NULLIF方法:如何避免除以零错误

SELECT [MyColumn] = sum( 
   case when v.Process_FundingDt 
   between @begDt and @endDt  
   and v.Loan_Purpose_Desc = 'PURCHASE' 
   then v.Loan_LoanAmt 
   else 0 
   end
 ) / NULLIF(sum (
   case when v.Process_FundingDt 
   between @begDt and @endDt 
   then v.Loan_LoanAmt else 0 
   end, 0)
 )
于 2016-08-31T13:45:01.503 回答