SQL Server – transactions roll back on error

BEGIN TRY
BEGIN TRANSACTION

INSERT INTO myTable (myColumns …) VALUES (myValues …);
INSERT INTO myTable (myColumns …) VALUES (myValues …);
INSERT INTO myTable (myColumns …) VALUES (myValues …);

COMMIT TRAN — Transaction Success!
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN –RollBack in case of Error

— you can Raise ERROR with RAISEERROR() Statement including the details of the exception
RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)
END CATCH

Advertisements