如何使用c#从数据库获取Max id?

时间:2014-04-22 10:30:13

标签: c#

cmd = new OleDbCommand("SELECT max(substr(tr_refno,9,6))as REFID from ECHALLAN WHERE DEPT='" +tmpDept.ToString() + "' and substr(tr_refno,5,2) ='" + Tmpmonth + "'", con);                         
maxid = Convert.ToInt16( cmd.ExecuteScalar());
  

错误= InvalidCastException未被用户代码

处理

2 个答案:

答案 0 :(得分:1)

在转换之前,您可以检查无效:

var value = cmd.ExecuteScalar();
int maxI;
If(value !=null)
   maxId = Convert.ToInt32(value);
else 
//......................

答案 1 :(得分:0)

尝试此命令:

cmd = new OleDbCommand("SELECT Max(COALESCE(substr(tr_refno,9,6),0)) as REFID from ECHALLAN WHERE DEPT='" +tmpDept.ToString() + "' and substr(tr_refno,5,2) ='" + Tmpmonth + "'", con);