NullIf()防止除零

时间:2011-12-27 21:10:03

标签: sql divide-by-zero

在我的查询中,在计算平均值时,我会遇到除以零的错误。我试图通过使用Nullif解决这个问题,但我不认为我的语法是正确的,因为Coldfusion会在')'附近发出错误声明错误的语法。

我的查询是:

<cfquery name="getValueAdd" datasource="#myDSN#">
    select d.partnum, sum(docunitprice * orderqty) as total_sales, 
    sum((c.avglaborcost + c.avgburdencost + c.avgmaterialcost + c.avgsubcontcost + c.avgmtlburcost)*d.orderqty) as total_cost,
    sum((docunitprice * orderqty)-((c.avglaborcost + c.avgburdencost + c.avgmaterialcost + c.avgsubcontcost + c.avgmtlburcost)*d.orderqty)) as Value_add,
   avg (isNull(
((((docunitprice * orderqty)-((c.avglaborcost + c.avgburdencost + c.avgmaterialcost + c.avgsubcontcost + c.avgmtlburcost)*d.orderqty))/ (nullIf(docunitprice * orderqty), 0),0)
))) as PercValueAdd
    from orderhed h with(nolock), orderdtl d with(nolock), partcost c with(nolock)
    where h.company = 'PC68300'
    and d.company = h.company
    and c.company = h.company
    and d.ordernum = h.ordernum
    and c.partnum = d.partnum
    and hdcasenum =  <cfqueryparam cfsqltype="cf_sql_integer" value="#rc.hdcasenum#" />   
    group by d.partnum
</cfquery>

有人可以为我澄清语法吗?

1 个答案:

答案 0 :(得分:3)

NullIf()有两个参数。您是否搜索了NullIf()文档?

  

如果两个表达式不是,则NULLIF返回第一个表达式   等于。如果表达式相等,则NULLIF返回null值   第一个表达式的类型。

以下是一个示例:http://www.bennadel.com/blog/984-Using-NULLIF-To-Prevent-Divide-By-Zero-Errors-In-SQL.htm