如何在asp.net razor中修复除零

时间:2014-03-15 08:55:59

标签: asp.net sql razor

我有一组运行如下的查询字符串:

var nq = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate())");  
var nrt = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate()) and OPPORTUNITY_STAGE = '-1'");  
var nrep = nrt / nq;

所有它给我的是未处理的例外:不能除以零。

前两个查询结果中的任何一个或两个都经常会出现零。如何让它显示NaN(不是数字)而不是崩溃?

我确定我之前已经问过这个,但我似乎无法找到答案。

提前致谢。

2 个答案:

答案 0 :(得分:1)

如何添加IF条件?

var nq = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate())");

var nrep = 0;
if (nq != 0)
{
var nrt = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate()) and OPPORTUNITY_STAGE = '-1'");
nrep = nrt / nq;
}

答案 1 :(得分:1)

您可以简单地替换

var nrep = nrt / nq;

Double nrep = Double.NaN;
if (nq != 0)
{
    nrep = nrt / nq;
}