Sql server 问题?

代码如下,

主要就是,意思是先差标的一列的最大值,然后把这个最大值+1,然后在构造sql语句插入数据,两个sql语句是在事务中完成,但是多个客户端同事,调用这段代码是,MaxBoxIndex这个会出现重复,怎么解决啊,有什么好方法不?

   for (int i = 0; i < list.Count; i++)
                {
                    model = (Model.tbCustBoxInfo)list[i];
                    string strCCGC = @"insert into dbo.tbCustBoxInfo(OrderType,OrderID,CustID,BoxCode,WholeBox,Proline,Sorter,BoxIndex,SortTime)
                                               values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',GetDate())";
                    strSQL = string.Format(strCCGC,model.OrderType, model.OrderID, model.CustID, model.BoxCode, model.WholeBox, model.ProLine, model.Sorter, GetMaxID(model.OrderID));
                    SQL_List.Add(strSQL);
                }
                using (IDatabase database = DatabaseFactory.CreateDatabase("DbConnStr"))
                {
                    database.ExecuteNonQuery(SQL_List, true);//true 表示开事务
                    return true;
                }

 

 public int GetMaxID(string OrderID)
        {
            string strSQL=@"select isNull(Max(BoxIndex),0)+1 as MaxBoxIndex from tbCustBoxInfo where OrderID=@OrderID";
            DataTable dtable = new DataTable();
            int iMaxID = 1;
            using (IDatabase database = DatabaseFactory.CreateDatabase("DbConnStr"))
            {
                using(ICommand cmd = database.CreateCommand(strSQL))
                {
                    cmd.AddInParameter("@OrderID",OrderID);
                    dtable = database.ExecuteDataTable(cmd);
                }
            }
            if (dtable != null && dtable.Rows.Count > 0)
            {
                try
                {
                    iMaxID = Convert.ToInt16(dtable.Rows[0][0].ToString());
                }
                catch (Exception ex)
                {
                    iMaxID = 1;
                }
            }
            return iMaxID;
        }

蛊毒传说
浏览 548回答 6
6回答

狐的传说

能自增长,当然是最好,我是没想到可行,那一列 不是唯一的,是更具自己的单号而自动增长

绝地无双

Insert语句中你知道使用GetDate() 那为什么不直接把select isNull(Max(BoxIndex),0)+1 as MaxBoxIndex from tbCustBoxInfo whereOrderID=@OrderID  放到insert里面去
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server