diff --git a/rebuild/rebuild_lastprice.ms.sql b/rebuild/rebuild_lastprice.ms.sql index dbbe8bd..48daa28 100644 --- a/rebuild/rebuild_lastprice.ms.sql +++ b/rebuild/rebuild_lastprice.ms.sql @@ -1,7 +1,11 @@ CREATE OR ALTER PROCEDURE pricing.rebuild_lastprice AS BEGIN - SET NOCOUNT ON; + SET NOCOUNT ON; + SET XACT_ABORT ON; -- auto-rollback on most errors + + BEGIN TRY + BEGIN TRAN; -- start transaction -------------------------------------------------------------------------------- -- Reset target tables -------------------------------------------------------------------------------- @@ -247,4 +251,25 @@ SELECT FROM flag_json f FULL OUTER JOIN seg_json s ON f.customer = s.customer AND f.partgroup = s.partgroup; + +-------------------------------------------------------------------------------- +-- Commit if everything succeeded +-------------------------------------------------------------------------------- +COMMIT TRAN; +END TRY +BEGIN CATCH + -- Ensure transaction is rolled back + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRAN; + END + + -- Optional: cleanup temp table (temp table persists for session until proc end, + -- but explicit drop is helpful if you reuse names or want to free resources) + IF OBJECT_ID('tempdb..#flagged') IS NOT NULL + DROP TABLE #flagged; + + -- Rethrow the original error to the caller + THROW; +END CATCH; END;