I have the below code. This code catches any error in the script while it's being executed and rolls back all the changes that were made from the start. This solves my problem of rolling back the transactions if anything happens.
My question is if I have to write a rollback script(which can be used later on after testing the application) for all the transactions I made during this script execution do I need to go statement by statement and do the exact opposite
Eg - in main script I do Insert Into Star Values 1 then in rollback script I do delete from star where id = 1 or is there some other automated way of doing it.
Like we can can call the SQL Server transaction log somehow and tell it to reverse the transactions it did during our script execution later on.
--This works to roll back the changes during script execution
SET XACT_ABORT ON;
GO
BEGIN TRANSACTION
-- Batch 1
BEGIN TRY
CREATE TABLE Persons (
PersonID int
);
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH;
GO
-- Commit transaction
IF XACT_STATE() = 1
BEGIN
COMMIT TRANSACTION;
PRINT 'Transaction committed.';
END;
Ultimately this is what I want is to rollback the updates my script made at a later point in time..say 3 days after..So I run my script today and it makes a bunch of changes..After 3 days using the application I sense something is wrong so I want to undo all the changes that the script did.