文档详情

SQLSERVER中处理分母为0的情况.docx

发布:2017-06-08约1.48千字共2页下载文档
文本预览下载声明
首先写个测试数据,然后我们来求一下colone除以coltwo的商declare?@table?table?(id?int,colone?numeric(4,2),coltwo?numeric(2,1))insert?into?@tableselect?1,1.2,0.4?union?allselect?2,1.4,0.6?union?allselect?3,1.8,0.8?union?allselect?4,9.1,1.2?union?allselect?5,9.02,2.9?union?allselect?6,9.11,3.4?union?allselect?7,8.23,2.3?union?allselect?8,12.11,0?union?allselect?9,2.3,8.1?union?allselect?10,2.5,0?我们来看一下数据表中的数据:select?*?from?@table/*id??????????colone??????????????????????????????????coltwo----------- ---------------------------------------1???????????1.20????????????????????????????????????0.42???????????1.40????????????????????????????????????0.63???????????1.80????????????????????????????????????0.84???????????9.10????????????????????????????????????1.25???????????9.02????????????????????????????????????2.96???????????9.11????????????????????????????????????3.47???????????8.23????????????????????????????????????2.38???????????12.11???????????????????????????????????0.09???????????2.30????????????????????????????????????8.110??????????2.50????????????????????????????????????0.0*/?如果直接这样写会报错:select colone/coltwo from @table错误信息:Divide by zero error encountered.?怎么来处理这个问题呢??--方法一:case whenselect?round(colone/case?coltwo?when?0?then?null?else?coltwo?end,2)?as?result1?from?@table/*result1---------------------------------------3.0000002.3300002.2500007.5800003.1100002.6800003.580000NULL*/--方法二:nullifselect?round(colone/nullif(coltwo,0),2)?as?result2?from?@table/*result2---------------------------------------3.0000002.3300002.2500007.5800003.1100002.6800003.580000NULL0.280000NULL*/?如果我们不想让分母为0的返回null的话,我们可以处理分母为1
显示全部
相似文档