Tuesday, September 19, 2006

You Can Rollback Tables That You Have Truncated (Inside A Transaction)

There seems to be a misconception that when you issue a TRUNCATE command against a table you will not be able to roll back.
That simply is not true; TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.
What does this mean? This means that SQL Server will use the mimimum amount of logging that it can to delete the data and still make it recoverable. in contrast to that the DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row

You see why TRUNCATE is so much faster; it deals with pages not with rows. and we all know that 1 extent is 8 pages and a page is 8K and can hold 8060 bytes. Well if you rows are 20 bytes wide then you need to log 403 delete statements with DELETE but TRUNCATE just uses a pointer to the page

So let's see how that works

--Create the table and inser 6 values
CREATE TABLE RollBacktest(id INT)
INSERT RollBacktest VALUES( 1 )
INSERT RollBacktest VALUES( 2 )
INSERT RollBacktest VALUES( 3 )
INSERT RollBacktest VALUES( 4 )
INSERT RollBacktest VALUES( 5 )
INSERT RollBacktest VALUES( 6 )
GO

--Should be 6 rows
SELECT 'Before The Transaction',* FROM RollBacktest

BEGIN TRAN RollBackTestTran
TRUNCATE TABLE RollBacktest

--Should be empty resultset
SELECT * FROM RollBacktest

--should be 0
SELECT COUNT(*) AS 'TruncatedCount' FROM RollBacktest

ROLLBACK TRAN RollBackTestTran

--Yes it is 6 again
SELECT 'ROLLED BACK',* FROM RollBacktest

DROP TABLE RollBacktest

No comments: