Ok so I am new here 🙂 I am relatively new to SQL, and I am trying to insert data into multiple tables. I have both inserts to work however I want it so if one fails neither are committed.
The tables look like this:
Student –
StudentID – int PK,
StudentName – Varchar,
etc …
Class –
ClassID – int PK,
ClassName – varchar,
etc…
StudentClass –
StudentID,
ClassID,
What I am trying to do is create a new Student whom can belong to multiple classes. So I have created the Student class table to break up the many-many relationship. I have a stored procedure to insert a new student and return the newest StudentID and then I use this StudentID, in a new stored procedure, and a table value parameter to insert multiple rows into StudentClass table. These are the stored procedures:
Create A Student:
@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()
Add Multiple Rows To StudentClass Table:
(@StudentClassCollection As InsertStudentClass READONLY)
INSERT INTO StudentClass(StudentID, ClassID)
SELECT StudentID, ClassID FROM @StudentClassCollection
So both of these work however I don’t know how to make it so if one fails the other will not execute and changes will not be committed? So effectively I need to perform both actions one after the other in the same stored procedure? I think! As I said I am new so if I have done anything wrong please let me know I will correct it 🙂
try like the below