2

启动此 SQL 查询时出现除以零错误:

SELECT CONVERT(VARCHAR(11),CaptureTime,106) 'CaptureTime',
        Type,
        CASE WHEN Unit='g/L' THEN (data1* 0.02586) ELSE data1 END As data1,
        CASE WHEN Unit='g/L' THEN nullif(data2* 0.02586,0) ELSE data2 END As data2,
        CASE WHEN Unit='g/L' THEN nullif(data3* 0.02586,0) ELSE data3 END As data3,
        CASE WHEN Unit='g/L' THEN nullif(data1* 0.02586,0) / nullif(data2* 0.02586,0) ELSE (data1/data2) END As Ratio,
        CASE WHEN Unit='g/L' THEN 'ml/L' ELSE 'ml/L' END As data,
        CASE WHEN Unit='g/L' THEN (data4* 0.01129) ELSE data4 END As data4
FROM something 
where Type ='DATA'
and ID='" + Session["name"].ToString() + "'
Order By CONVERT(DateTime, CaptureTime,101) DESC
4

2 回答 2

3

错误几乎肯定来自这里的第二行:

CASE WHEN Unit='g/L' THEN nullif(data1* 0.02586,0) / nullif(data2* 0.02586,0) " +
    "ELSE (data1/data2)" +  
    "END As Ratio,"

如果单位不是 G/L 且 data2 为 0,则会出现错误。将其更改为:

CASE WHEN Unit='g/L' THEN nullif(data1* 0.02586,0) / nullif(data2* 0.02586,0) " +
    "ELSE (data1/NULLIF(data2, 0))" +  
    "END As Ratio,"
于 2012-10-30T09:56:14.733 回答
0

如果 data2 等于零,则无法计算比率,因为您不能除以零,它将始终输出错误消息。

我建议你添加一个案例:

CASE WHEN data2=0 
THEN 0
ELSE
    CASE WHEN Unit='g/L' 
    THEN (data1 * 0.02586) / (data2 * 0.02586) 
    ELSE data1/data2
    END 
END As Ratio,
于 2012-10-30T09:53:35.787 回答