In this blog post, we explore the use of TRY...CATCH blocks in SQL Server to manage transactions effectively. Learn how to handle errors gracefully and ensure data integrity with practical examples and best practices.
BEGIN TRY
BEGIN TRAN
-- Add your SQL DDL/DML statements here
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH