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

本文关键字:数据 插入 第一个 另一个 SQL+C# 存储过程 一个 然后 | 更新日期: 2023-09-27 18:26:58

好的,所以我在这里是新手:)我对SQL相对陌生,我正在尝试将数据插入多个表中。我有两个插件可以工作,但我希望它,所以如果其中一个失败,两个都不提交。表格如下:

学生-StudentID-int PK,StudentName-Varchar,等

类别-ClassID-int PK,ClassName-varchar,等等。

学生类别-StudentID,ClassID,

我想做的是创建一个可以属于多个班级的新学生。因此,我创建了学生班级表,以打破许多许多关系。我有一个存储过程来插入一个新学生并返回最新的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

所以这两种方法都有效,但我不知道如何做到这一点,如果其中一个失败,另一个就不会执行,也不会提交更改?因此,我需要在同一存储过程中一个接一个地执行这两个操作,这是否有效?我想!正如我所说,我是新来的,所以如果我做错了什么,请告诉我我会纠正:)

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

如果出现错误,将自动发出回滚

SET XACT_ABORT ON
begin transaction
-- YOUR WORK HERE
commit transaction

像下面的一样尝试

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();
     }  
   }
begin tran
// all insert , update script here    

IF @@ERROR <> 0
BEGIN
    ROLLBACK tran
END
ELSE
    commit tran