How can I rollback an UPDATE query in SQL server 2005?

后端 未结 10 2368
北海茫月
北海茫月 2020-12-14 09:15

How can I rollback an UPDATE query in SQL server 2005?

I need to do this in SQL, not through code.

相关标签:
10条回答
  • 2020-12-14 09:16

    in this example we run 2 line insert into query and if all of them true it run but if not no run anything and ROLLBACK

    DECLARE @rowcount int  set @rowcount = 0 ; 
    BEGIN TRANSACTION [Tran1]
    BEGIN TRY 
     insert into [database].[dbo].[tbl1] (fld1) values('1') ;
        set @rowcount = (@rowcount + @@ROWCOUNT); 
     insert into [database].[dbo].[tbl2] (fld1) values('2') ;
        set @rowcount = (@rowcount + @@ROWCOUNT); 
    
    IF @rowcount =  2
      COMMIT TRANSACTION[Tran1]
    ELSE
      ROLLBACK TRANSACTION[Tran1]
    END TRY
      BEGIN CATCH
      ROLLBACK TRANSACTION[Tran1]
    END CATCH
    
    0 讨论(0)
  • 2020-12-14 09:23

    Once an update is committed you can't rollback just the single update. Your best bet is to roll back to a previous backup of the database.

    0 讨论(0)
  • 2020-12-14 09:24

    You need this tool and you can find the transaction and reverse it.

    ApexSQL Log

    0 讨论(0)
  • 2020-12-14 09:27

    Try

    ROLLBACK WORK;
    

    It usually works

    0 讨论(0)
  • 2020-12-14 09:32

    You can rollback the statements you've executed within a transaction. Instead of commiting the transaction, rollback the transaction.

    If you have updated something and want to rollback those updates, and you haven't done this inside a (not-yet-commited) transaction, then I think it's though luck ...

    (Manually repair, or, restore backups)

    0 讨论(0)
  • 2020-12-14 09:33

    Simple to do:

    header code...

    Set objMyConn = New ADODB.Connection
    
    Set objMyCmd = New ADODB.Command Set
    
    objMyRecordset = New ADODB.Recordset
    
    On Error GoTo ERRORHAND 
    

    Working code...

    objMyConn.ConnectionString = ConnStr
    
    objMyConn.Open 
    

    code....

    'Copy Data FROM Excel'

    objMyConn.BeginTrans <-- define transactions to possible be rolled back 
    
    For NewRows = 2 To Rows
    
    objMyRecordset.AddNew 
    
    For NewColumns = 0 To Columns - 1
    
    objMyRecordset.Fields(NewColumns).Value = ActiveSheet.Cells(NewRows, NewColumns + 1)
    
    Next NewColumns objMyRecordset.Update Next NewRows
    
    objMyConn.CommitTrans <- if success, commit them to DB
    
    objMyConn.Close
    

    ERRORHAND:

    Success = False 
    
    objMyConn.RollbackTrans <-- here we roll back if error encountered somewhere
    
    LogMessage = "ERROR writing database: " & Err.Description
    

    ...

    0 讨论(0)
提交回复
热议问题