![](/img/trans.png)
[英]Getting data from xml and inserting into existing table using stored procedure and c#
[英]Inserting data into one table then multiple rows into another using data from the first using stored procedures (SQL + C#)
好的,所以我在这里很新:)我对SQL比较陌生,我正在尝试将数据插入到多个表中。 我有两个插入件都可以工作,但是我想要这样,所以如果一个插入失败,则不会提交。 这些表如下所示:
学生-StudentID-int PK,StudentName-Varchar等...
类-ClassID-整型PK,类名-varchar等
StudentClass-StudentID,ClassID,
我想做的是创建一个可以属于多个班级的新学生。 因此,我创建了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
因此,这两项工作都无法实现,因此如果一个失败,另一个将无法执行,更改也不会提交? 如此有效,我需要在同一存储过程中一个接一个地执行这两个动作吗? 我认为! 正如我所说的,我是新手,所以如果我做错了什么,请让我知道我将纠正它:)
SET XACT_ABORT ON
begin transaction
-- YOUR WORK HERE
commit transaction
begin tran
// all insert , update script here
IF @@ERROR <> 0
BEGIN
ROLLBACK tran
END
ELSE
commit tran
尝试如下
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.