Wednesday, 7 June 2017

A Myth - Truncate and Drop operation can't be rolled Back

We all know Delete is a DML command and it can be rolled back bu using it in the transaction.
But always we have heard, read, practiced and believed to be a MYTH that Truncate and Drop operation can't be rolled Back. But in reality these two operations can also be rolled back and yes it is against to the RDBMS concept itself.

Follow the below steps to witness this.

1. Create a table

 Use AdventureWorks2012

GO 

CREATE TABLE [dbo].[Drop_test](
[id] [int]  NOT NULL,
[name] [varchar](100) NULL
) ON [PRIMARY]

GO


2. Insert a dummy data

Insert into [dbo].[Drop_test]
values (1, 'a') 



3. Check the row count

select * from [dbo].[Drop_test]

4. Truncate the table by using it within a transaction.

begin tran 

truncate table [dbo].[Drop_test]

--commit tran 

Check the row count

select * from [dbo].[Drop_test]

6. Roll Back the transaction and you can get back all the data which was deleted.

Rollback tran 

7. Same steps can be used to verify the Drop Table operation.

begin tran 

drop table  [dbo].[Drop_test]

ROllback tran 










No comments:

Post a Comment