'Raiserror severity 16 does not rollbacks trigger
I have a database running on SQL Server 2008.
I have a trigger in which I raise error with severity 16. When I test the trigger the error appears but the operation is not rolled back, i.e. I have additional row in the table. I can not understand why is that, because severity 16 results in rollback. We also used that convention in other triggers and it terminates trigger and causes rollback.
The table has also another trigger which does not allow deletion of rows.
Here is the trigger:
ALTER TRIGGER dbo.trg
ON dbo.tbl
AFTER INSERT, UPDATE
AS
BEGIN
IF (@@ROWCOUNT > 0)
IF ((SELECT COUNT(SDS.ID) AS Count0 FROM dbo.tbl SDS WHERE SDS.IsIdleTimeReferred = 0) <> 1) OR
((SELECT MAX(SDS.CreatedDate) FROM dbo.tbl SDS WHERE SDS.IsIdleTimeReferred = 0) <
(SELECT MAX(SDS.CreatedDate) FROM dbo.tbl SDS WHERE SDS.IsIdleTimeReferred = 1))
BEGIN
--IF @@TRANCOUNT > 0 ROLLBACK
RAISERROR('Only one record with value IsIdleTimeReferred=0 must exist and it must be the last one', 16, 1);
END;
END;
When I uncomment @@TRANCOUNT the operation behaves correctly.
The table tbl consists of 3 columns:
[ID], [IsIdleTimeReferred], [CreatedDate]
I can not figure out where is the problem. For me code is designed correctly.
Any ideas?
EDIT:
Ok, I agree that Severity 16 does not rollback transaction in a trigger. So I implemented the following code (the trigger is AFTER INSERT, UPDATE):
BEGIN
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
RAISERROR('Does not allow modifications in the past', 16, 1);
RETURN;
END;
This code does not rollbacks transaction in a trigger. If I switch rows and first RAISERROR and then ROLLBACK the changes are not rollbacked.
Why this happening?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
