机房收费系统统计一个操作员结账情况时,对充值、退卡、收费进行求和查询。
报错
我的D层没毛病的代码是这样写的:
SqlHelper.sqlhelper sqlhelper = new SqlHelper.sqlhelper();
SqlParameter[] SqlParams1 = { new SqlParameter("@UserID", informain.Username),
new SqlParameter("@status", "未结账")};
string Sql1 = "select sum(addmoney) from ReCharge where status=@status and UserID=@UserID";
DataTable table = sqlhelper.getDataTable(Sql1, CommandType.Text, SqlParams1);
informain.cash = Convert.ToDecimal(table.Rows[0][0].ToString ());
操作员没有退卡或充值时金额就为0了。
奇怪的是当不存在符合条件的数据时也能查出一个格来,就报错了:
解决
思路是这样的:
找到出现这种情况的可能,直接给赋值为0。
但是判断这个格里到底是“”还是NULL呢?尴尬了,答案是都不是。
其实是sum(addmoney)在捣乱的,在这可以直接判断赋值给0的。把SQL语句写成这样:
select isnull(sum(addmoney),0) from ReCharge where status=@status and UserID=@UserID
这样当不存在符合条件的数据时就赋值为0。
总结:解决问题的思路很重要,思考问题的方式更重要。套路!