按订单日期与序号生成订单号 按订单日期与序号生成订单号

2016-06-11

 /// <summary>
    /// 生成12位订单号
    /// </summary>
    public string CreateOrder()
    {
        object obj = new object(); //锁对象
        int maxOrder = 0; //当日最大订单号
        int TodayDay = DateTime.Now.Day; //当日时间
        StringBuilder str = new StringBuilder();
        str.Append("");//订单开头
        str.Append(DateTime.Now.ToString("yyyyMMdd"));//订单中间时间
        lock (obj)
        {
            if (maxOrder == 0 || TodayDay != DateTime.Now.Day)
            {
                string Time = DateTime.Now.ToString("yyyy-MM-dd");// + " 00:00:00";
                string strSql = string.Format("select top 1 substring(SysNo,11,4) from Ton_MainCar where SysDatetime between '{0}' and '{1}' order by MID desc", Time + " 00:00:00", Time + " 23:59:59");//这句sql语句很重要
                using (SqlConnection conn = DBClass.GetConnection("KNetMeberSys"))
                {
                    SqlCommand cmd = new SqlCommand(strSql, conn);
                    conn.Open();
                    object orders = cmd.ExecuteScalar();
                    if (orders == null)
                        maxOrder = 1;
                    else
                        maxOrder = Convert.ToInt32(orders.ToString().TrimStart('0')) + 1;
                }
            }
            else
                maxOrder++;
        }
        str.Append(maxOrder.ToString().PadLeft(4, '0'));//4位不足的补0
        return str.ToString();
    }