【问题标题】:Inserting data into one table then multiple rows into another using data from the first using stored procedures (SQL + C#)使用存储过程(SQL + C#)将数据插入一个表,然后将多行插入另一个表
【发布时间】:2012-03-23 18:41:24
【问题描述】:

好的,所以我是新来的 :) 我对 SQL 比较陌生,我正在尝试将数据插入到多个表中。我有两个插入工作,但是我想要它,所以如果一个失败,两个都不会提交。 表格如下所示:

学生 - StudentID - 整数 PK, 学生姓名 - Varchar, 等等……

类 - ClassID - int PK, 类名 - varchar, 等等……

学生班 - 学生卡, 类 ID,

我要做的是创建一个可以属于多个班级的新学生。所以我创建了 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

所以这两项工作,但是我不知道如何做到这一点,所以如果一个失败,另一个将不会执行并且不会提交更改?如此有效地我需要在同一个存储过程中一个接一个地执行这两个操作?我想!正如我所说,我是新人,所以如果我做错了什么,请告诉我,我会纠正它:)

【问题讨论】:

    标签: c# sql visual-studio-2010 sql-server-2008 stored-procedures


    【解决方案1】:

    In case of an error, rollback will be issued automatically

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

    【讨论】:

    • 谢谢,不知道 XACT_ABORT 相信以后会有用!
    【解决方案2】:

    像下面这样尝试

    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();
         }  
       }
    

    【讨论】:

    【解决方案3】:
    begin tran
    
    // all insert , update script here    
    
    
    IF @@ERROR <> 0
    BEGIN
        ROLLBACK tran
    END
    ELSE
        commit tran
    

    【讨论】:

    • 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    相关资源
    最近更新 更多