编程语言
首页 > 编程语言> > c#利用事务获取刚插入的数据的ID

c#利用事务获取刚插入的数据的ID

作者:互联网

今天遇到了一个两个表或多个表关联同时插入数据的需求 ,主表插入一条数据,接着给子表插入数据时其中一个字段要存储与主表关联的id
所以要获取刚插入主表的那条数据的主键ID
我这里有两个数据库
主表: 主表id
子表:
子表orderid关联主表id
所以先要获取刚插入主表的那条数据的主键ID 在往子表里面添加数据
代码如下:

 public bool PreAdd(Model.PRO_Order model, List<Model.PRO_Order_Process> items)
        {
            using (SqlConnection connection = new SqlConnection(PubConstant.ConnectionString))
            {
                SqlTransaction transaction = null;
                try
                {
                    connection.Open();
                    //开启事务
                    transaction = connection.BeginTransaction();

                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("insert into PRO_Order(");
                    strSql.Append(
                        "Code,FZRID,FZRName,FinishDate,SaleOrders,GYLC,SCYL,CreateDateTime)");
                    strSql.Append(" values (");
                    strSql.Append(
                        "@Code,@FZRID,@FZRName,@FinishDate,@SaleOrders,@GYLC,@SCYL,@CreateDateTime);SELECT @@Identity;");
                    SqlParameter[] parameters =
                    {
                       new SqlParameter("@Code", SqlDbType.VarChar,500),
				       new SqlParameter("@FZRID", SqlDbType.Int,4),
					   new SqlParameter("@FZRName", SqlDbType.NVarChar,100),
					   new SqlParameter("@FinishDate", SqlDbType.Date),
					   new SqlParameter("@SaleOrders", SqlDbType.VarChar,4000),
					   new SqlParameter("@GYLC", SqlDbType.NVarChar),
					   new SqlParameter("@SCYL", SqlDbType.NVarChar),
					   new SqlParameter("@CreateDateTime", SqlDbType.DateTime)};

                    parameters[0].Value = model.Code;
                    parameters[1].Value = model.FZRID;
                    parameters[2].Value = model.FZRName;
                    parameters[3].Value = model.FinishDate;
                    parameters[4].Value = model.SaleOrders;
                    parameters[5].Value = model.GYLC;
                    parameters[6].Value = model.SCYL;
                    parameters[7].Value = model.CreateDateTime;

                    SqlCommand command = new SqlCommand(strSql.ToString(), connection, transaction);
                    command.Parameters.AddRange(parameters);
                    command.ExecuteNonQuery();
                    //获取主表id
                    int id =Convert.ToInt32(command.ExecuteScalar());
                     //插入行项目
                    strSql = new StringBuilder();
                    strSql.Append("insert into PRO_Order_Process(");
                    strSql.Append("OrderId,ProcessId,Sort,FZRID,FZRName,IsBG,ProcessName)");
                    strSql.Append(" values (");
                    strSql.Append("@OrderId,@ProcessId,@Sort,@FZRID,@FZRName,@IsBG,@ProcessName)");

                    foreach (var item in items)
                    {
                        parameters = new SqlParameter[]
                        {
                          new SqlParameter("@OrderId", SqlDbType.Int,4),
				     	  new SqlParameter("@ProcessId", SqlDbType.Int,4),
					      new SqlParameter("@Sort", SqlDbType.Int,4),
					      new SqlParameter("@FZRID", SqlDbType.Int,4),
					      new SqlParameter("@FZRName", SqlDbType.NVarChar,100),
					      new SqlParameter("@IsBG", SqlDbType.Bit,1),
                          new SqlParameter("@ProcessName", SqlDbType.NVarChar,100),
                        };

                        parameters[0].Value = id; 
                        parameters[1].Value = item.ProcessId;
                        parameters[2].Value = item.Sort;
                        parameters[3].Value = item.FZRID;
                        parameters[4].Value = item.FZRName;
                        parameters[5].Value = item.IsBG;
                        parameters[6].Value = item.ProcessName;

                        command = new SqlCommand(strSql.ToString(), connection, transaction);
                        command.Parameters.AddRange(parameters);
                        command.ExecuteNonQuery();

                    }
                    transaction.Commit();
                    return true;
                }
                catch (Exception)
                {
                    if (transaction != null)
                    {
                        transaction.Rollback();
                    }
                    throw;
                }
                finally
                {
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }

主要就开启事务之后, 添加语句的后面加上SELECT @@Identity,使用ExecuteScalar()获取返回值

 //开启事务
                    transaction = connection.BeginTransaction();

                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("insert into PRO_Order(");
                    strSql.Append(
                        "Code,FZRID,FZRName,FinishDate,SaleOrders,GYLC,SCYL,CreateDateTime)");
                    strSql.Append(" values (");
                    strSql.Append(
                        "@Code,@FZRID,@FZRName,@FinishDate,@SaleOrders,@GYLC,@SCYL,@CreateDateTime);SELECT @@Identity;");

获取主表id

  //获取主表id
                    int id =Convert.ToInt32(command.ExecuteScalar());

就能直接取到刚插入的数据id !

标签:SqlDbType,parameters,c#,Value,SqlParameter,插入,strSql,new,ID
来源: https://blog.csdn.net/WangFeiYang12138/article/details/107025048