简体   繁体   English

SQL Server事务回滚

[英]SQL Server Transaction rollback

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. 例如-在主脚本中,我将插入星值1,然后在回滚脚本中,我从id = 1的星号中删除,或者是否有其他自动方法。

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. 就像我们可以以某种方式调用SQL Server事务日志,并告诉它稍后在执行脚本期间撤消它所做的事务一样。

--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. 最终,这就是我想要回滚的脚本在以后某个时间点所做的更新。例如说3天之后。所以我今天运行我的脚本,它做了很多更改。使用该应用程序3天后感觉到有问题,所以我想撤消脚本所做的所有更改。

Based on your question, I am finding it a little difficult to determine your actual real world use case. 根据您的问题,我发现确定您实际的实际用例有些困难。 However, Database Snapshots MAY be an option for you. 但是,数据库快照可能是您的一个选择。 More details can be found in here in TechNet 可以在TechNet的此处找到更多详细信息

In the event of a user error on a source database, you can revert the source database to the state it was in when a given database snapshot was created. 如果源数据库上出现用户错误,则可以将源数据库还原为创建给定数据库快照时的状态。 Data loss is confined to updates to the database since the snapshot's creation. 自快照创建以来,数据丢失仅限于对数据库的更新。

However, the snapshot works at the DB level and would not be specific to the TRANSACTIONS initiated within your script, rather to all CRUD and DDL operations on the database. 但是,快照可以在数据库级别工作,而不是特定于脚本内启动的事务,而是特定于数据库上的所有CRUD和DDL操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM