Algorhythm
Algorhythm

Reputation: 570

Rolling Back A Transaction In T-SQL After Code Has Been Executed

I am trying to find a method to rollback a transaction after it has been executed.

For example:

DECLARE @tsubaki VARCHAR(25);
SET @tsubaki = 'A Transaction';

BEGIN TRANSACTION @tsubaki
UPDATE dbo.Maka SET id = 400, name = 'inu' --notice I didn't put there where clause
COMMIT TRANSACTION

Later on I realize that I updated everything in the databse Maka instead of just the one record I originally intended.

Now I try to write code to roll it back before the update:

DECLARE @tsubaki VARCHAR(25);
SET @tsubaki = 'A Transaction';
ROLLBACK TRANSACTION @tsubaki;

Doesn't work. Bottom line: I am looking for a way to rollback a sql transaction in MS-SQL Server 2008 after the transaction has been commit and the sql has ran.

Thanks in advance.

Upvotes: 2

Views: 464

Answers (1)

Paul Sasik
Paul Sasik

Reputation: 81537

You can't do that from T-SQL code. You will have to restore to a point in time from the log file. Note that the restore will "undo" everything to a point in time, including your transaction.

In the future you should ALWAYS back up your db before any manual update, small or large. You can also cover yourself with a little trick. Write out your update/delete code like this:

SELECT * FROM dbo.Maka
-- UPDATE dbo.Maka SET id = 400, name = 'inu'
WHERE some_identifier = some_value

Run the SELECT version first which is innocuous and when you can verify the record(s) to be updated select the code from the WHERE clause up to the UPDATE and run it.

Upvotes: 6

Related Questions