I am using a table value parameter in a stored proc to insert data to table1. The insert fires a trigger to insert data to table2. When one or more of the rows that is attempting to be inserted to table1 fails, the trigger inserting data to table 2 is not rolling backing the previous successful row(s) inserted, which is corrupting data.
So I need a solution to rollback the data from table 1 and table2 (which is being inserted to via a trigger on Table1) when there is an error on of any of the rows in the input table valued parameter. My test right now (see below) is trying to insert 2 rows to table 1. The first row is valid and inserts to table1 and a trigger fires which causes a insert to Table2. The 2nd row is failing due to overflow error, and isn't inserted to table 1 or 2, but the insert to Table2 for the first valid record in the dataset is NOT rolledback but is still in Table2.
Here is what I have tried:
Create MYTVPType as Table (
Col1 [smallint] Not null,
Col2 [smallint] Not null
)
Go
Create Trigger InsertTriggerForTable1 on Table1
for INSERT
as
insert into Table2 (Col1, Col2, StartTime, EndTime)
Select Col1, Col2, getdate(), null from Inserted
Go
Create Procedure Proc1
(@TVP MyTVPType READONLY)
as
Begin Try
Begin Tran
insert into Table1 (Col1, Col2)
Commit Tran
End Try
Begin Catch
Rollback Tran
RaisError ('unexpected error occured', 16,1)
End Catch
Go
example execution code to try to insert one invalid row and test rollback logic.
DECLARE @p MYTVPType
INSERT INTO @p VALUES (3, 20)
INSERT INTO @p VALUES (5, 500000)
EXEC sp_executesql N'Proc1 @TVP = @TVP', N'@TVP [dbo].[MYTVPType] READONLY',@TVP=@p