C# 使用存储过程(SQL+;C)将数据插入一个表,然后使用第一个表中的数据将多行插入另一个表

C# 使用存储过程(SQL+;C)将数据插入一个表,然后使用第一个表中的数据将多行插入另一个表,c#,sql,visual-studio-2010,sql-server-2008,stored-procedures,C#,Sql,Visual Studio 2010,Sql Server 2008,Stored Procedures,好的,我是新来的:)我对SQL比较陌生,我正在尝试将数据插入多个表中。我有两个插入工作,但我希望它,因此,如果一个失败,都没有提交。 这些表如下所示: 学生- StudentID-int PK, 学生姓名-Varchar, 等等 阶级- ClassID-int PK, 类名-varchar, 等等 学生班- 学生, ClassID 我想做的是创造一个可以属于多个班级的新学生。因此,我创建了Student class表来打破这种多方面的关系。我有一个存储过程来插入一个新的student并返回最新的

好的,我是新来的:)我对SQL比较陌生,我正在尝试将数据插入多个表中。我有两个插入工作,但我希望它,因此,如果一个失败,都没有提交。 这些表如下所示:

学生- StudentID-int PK, 学生姓名-Varchar, 等等

阶级- ClassID-int PK, 类名-varchar, 等等

学生班- 学生, ClassID

我想做的是创造一个可以属于多个班级的新学生。因此,我创建了Student class表来打破这种多方面的关系。我有一个存储过程来插入一个新的student并返回最新的StudentID,然后在一个新的存储过程中使用这个StudentID,还有一个表值参数来将多行插入StudentClass表中。以下是存储过程:

创建一个学生:

@FirstName varchar(20) = '', 
@LastName varchar(20) = '',
@PredictedGrade char(1) = '',
@ActionPlan bit = 0,
@StudentActive bit = 1,
@StudentID int out

INSERT INTO Student (FirstName, LastName, PredictedGrade, ActionPlan, StudentActive)
VALUES (@FirstName, @LastName, @PredictedGrade, @ActionPlan, @StudentActive)
SET @StudentID = SCOPE_IDENTITY()
将多行添加到StudentClass表:

(@StudentClassCollection As InsertStudentClass READONLY)

INSERT INTO StudentClass(StudentID, ClassID)
SELECT StudentID, ClassID FROM @StudentClassCollection
因此,这两项工作,但我不知道如何使它,如果一个失败,另一个将不会执行和更改将不会提交?所以我需要在同一个存储过程中一个接一个地执行这两个操作?我想!正如我所说,我是新来的,所以如果我做错了什么,请让我知道我会纠正它:)

begin tran
//在此处插入、更新所有脚本
如果@错误0
开始
回滚传输
结束
其他的
提交传输
尝试以下方法

using (SqlConnection  connection= new SqlConnection(connectionstring))
   {
     connection.Open();
     SqlTransaction transaction = connection.BeginTransaction();
     try
     {
        SqlCommand command = new SqlCommand("proc1",connection);
        //execute the above command
        command.CommandText="proc2";
        //execute command again for proc2
        transaction.Commit();                   
     }
     catch
     {
       //Roll back the transaction.
       transaction.Rollback();
     }  
   }


非常感谢,这看起来是最好的方法,因为我可以继续使用我现有的存储过程:)我本来会投票的,但我还不能!您可以接受答案谢谢,不知道XACT_ABORT我相信它将来会有用的!非常感谢你的帮助!
using (SqlConnection  connection= new SqlConnection(connectionstring))
   {
     connection.Open();
     SqlTransaction transaction = connection.BeginTransaction();
     try
     {
        SqlCommand command = new SqlCommand("proc1",connection);
        //execute the above command
        command.CommandText="proc2";
        //execute command again for proc2
        transaction.Commit();                   
     }
     catch
     {
       //Roll back the transaction.
       transaction.Rollback();
     }  
   }
SET XACT_ABORT ON

begin transaction

-- YOUR WORK HERE

commit transaction