Search code examples
sqlsql-serverforeign-keyssql-updaterevert

How to revert update query in sql server?


I am using SQL Server for my database. now there is table which has following columns.

PK_ID   FK_ID   Name   Description
1        5       ABC      ABCDE
2        7       EFG      EFT
3        8       XUZ      Xyz
4        11      TEF      TEF

Now by mistake i update some Fk_ID field with null value. Now I want to get back my all fk_id which is updated by null value. So is there any way to revert back fk_id's which has value previously?

Can any one help me out to find out solution for the same?


Solution

  • To avoid this in the future, you may want to use a transaction to give you the option to roll back.

    For example

    BEGIN TRAN T1;
    UPDATE ImportantStuff SET ImportantValue = 1 WHERE SomeValue = 5
    

    You can then either commit if it looks good:

    COMMIT TRAN T1;
    

    Or rollback if it doesn't

    ROLLBACK TRAN T1
    

    Of course, this is not a substitute for testing before you run a script against real data - but I have often used this during testing, rather than hoping for the best.

    Without a transaction, you will need to reset the data from a back up.