日期:2014-05-18 浏览次数:20922 次
string sql = @" Insert into A(A1,A2) values(@A1,@A2); select @@IDENTITY AS 'Identity'; Insert into B(B1,B2,B3) values(@B1,@B2,@B3)"; SqlConnection conn = new SqlConnection(CONNECT_STRING); SqlTransaction tran = null; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; try { conn.Open(); tran = conn.BeginTransaction(); cmd.Transaction = tran; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@A1", A1); ... cmd.CommandText = sql; cmd.ExecuteNonQuery(); tran.Commit(); return true; } catch (Exception ex) { if (tran != null) { tran.Rollback(); } return false; } finally { conn.Close(); cmd.Dispose(); }
string sql = "insert into a(a2) values('a');" + "declare @id int;" + "select @id=@@IDENTITY;" + "insert into b(b1,b2,b3) values(@id,'b2','b3');";