假如我有2个表   主表   id,name,pass   从表  id,type,size
有一组数据  "张三",“123”,“1”,“22”
同时插入2个表当中。怎么做??
请问是在DAL层 写2个插入方法在BLL层调用2个吗?
还是直接写一个SQL语句??
求高手。。最好不用存储过程。拜谢
             

解决方案 »

  1.   

    先主表insert into Tb(id,name,pass) values(@id,@name,@pass);select @@identity;
     再从表
    使用TransactionScope 事务操作
      

  2.   

    执行这个会返回id   insert into Tb(id,name,pass) values(@id,@name,@pass);select @@identity;
    在insert into 从表 values(...)就可以了
      

  3.   

    使用TransactionScope 事务操作
    怎么做啊  
      

  4.   

    如果不用存储过程的话,至少要写2条sql语句把。至于方法,你可以把这2条语句封装成一个方法sql 1: insert data to 主表, then output IDsql 2: insert data to 从表 using sql 1 's ID
      

  5.   

    楼主如果使用三层架构的话就得在bll和dal层都写方法调用了,但是同样需要事务处理,应该做到两个表都插入时才提交事务,否则两个表都不插入数据
      

  6.   

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True");
                con.Open();
                ///创建命令
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "insert into A(name)values('name')";
                ///开始事物,并上锁
                System.Data.SqlClient.SqlTransaction tran = con.BeginTransaction(System.Data.IsolationLevel.Serializable);
                try
                {
                    cmd.Transaction = tran;
                    cmd.ExecuteNonQuery();
                    tran.Commit();
                    Console.WriteLine("Commit");
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Error:" + ex.Message);
                    tran.Rollback();
                    Console.WriteLine("Rollback");
                }
                finally
                {
                    con.Close();
                }
                Console.ReadLine();
    恩,这是一个事物,你把里面的语句改成插入两条sql语句就好了。