有没有办法回滚事务中的特定保存点?

时间:2018-09-27 11:59:53

标签: sql-server transactions

假设我有带有三个保存点的SQL事务,如下所示:

BEGIN TRANSACTION 
--Insert Value 1
SAVE TRANSACTION FirstInsert -- 1st Save Point
--Insert Value 2
SAVE TRANSACTION SecondInsert -- 2nd Save Point
--Insert Value 3 
SAVE TRANSACTION ThirdInsert -- 3rd Save Point
--Insert Value 4
ROLLBACK TRANSACTION SecondInsert 
COMMIT

如果我回滚“ SecondInsert”保存点,则第4个插入值也会回滚。有没有办法只回退SecondInsert保存点?这样插入的第4个值将保留在表格中。

CREATE TABLE TestTable
(
   ID INT NOT NULL,
   Value INT NOT NULL,
   PRIMARY KEY (ID)
)
GO
TRUNCATE TABLE TestTable; 
DECLARE @vSecondInsert NCHAR(50)='SecondInsert' 
BEGIN TRANSACTION  
   INSERT INTO TestTable( ID, Value )   VALUES  ( 1, N'10')
   -- this will create a savepoint after the first INSERT
   SAVE TRANSACTION FirstInsert 
   INSERT INTO TestTable( ID, Value )   VALUES  ( 2, N'20')
   -- this will create a savepoint after the second INSERT
   SAVE TRANSACTION @vSecondInsert
   INSERT INTO TestTable( ID, Value )   VALUES  ( 3, N'30') 
   SAVE TRANSACTION ThirdInsert
   INSERT INTO TestTable( ID, Value )   VALUES  ( 4, N'40')
   ROLLBACK TRANSACTION @vSecondInsert 
COMMIT 
SELECT * FROM TestTable

0 个答案:

没有答案