下面给出对于向数据库中插入数据时,有不规则自增列通常的处理方法,这里得自增列为requestid其自增规则如下:
R000001、R000002、R000003······
protected string GetRequestid()
{
string sql = @"select MAX(SUBSTRING(requestid,2,LEN(requestid)-1)+1) from RequestPaper"; //此处不规则自增字段为requestid
object a;
using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
a = cmd.ExecuteScalar(); // 得到最后的数字 ,即如果最后的R000003,则得到的a值为3
}
}
string requestid = "R" + a.ToString().PadLeft(6, '0'); //PadLeft方法为在共六位,在左侧开始补0,补齐6位数字
return requestid;
}