Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recover data from truncated table

while going though sql server interview question in book of mr. shiv prashad koirala. i got to know that, even after using truncate table command the data can be recovered.

please tell me how can we recover data when data is deleted using 'delete' command and how can data be recover if data is deleted using 'truncate' command.

what i know is that when we use delete command to delete records the entry of it is made in log file but i don't know how to recover the data from and as i read that truncate table not enters any log entry in database then how can that also be recovered.

if you can give me any good link to do it practically step by step than that will be great help to me.

i have got sql server 2008.

Thanks

like image 626
Dr. Rajesh Rolen Avatar asked Nov 16 '10 10:11

Dr. Rajesh Rolen


2 Answers

If you use TRANSACTIONS in your code, TRUNCATE can be rolled back. If there is no transaction is used and TRUNCATE operation is committed, it can not be retrieved from log file. TRUNCATE is DDL operation and it is not logged in log file.

DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION if the current session is not closed. If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if session is closed, it can not be rolled back but DELETE can be rolled back.

USE tempdb
GO
-- Create Test Table
CREATE TABLE TruncateTest (ID INT)
INSERT INTO TruncateTest (ID)
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
GO
-- Check the data before truncate
SELECT * FROM TruncateTest
GO
-- Begin Transaction
BEGIN TRAN
-- Truncate Table
TRUNCATE TABLE TruncateTest
GO
-- Check the data after truncate
SELECT * FROM TruncateTest
GO
-- Rollback Transaction
ROLLBACK TRAN
GO
-- Check the data after Rollback
SELECT * FROM TruncateTest
GO
-- Clean up
DROP TABLE TruncateTest
GO
like image 119
Pankaj Agarwal Avatar answered Oct 11 '22 12:10

Pankaj Agarwal


By default none of these two can be reverted but there are special cases when this is possible.

Truncate: when truncate is executed SQL Server doesn’t delete data but only deallocates pages. This means that if you can still read these pages (using query or third party tool) there is a possibility to recover data. However you need to act fast before these pages are overwritten.

Delete: If database is in full recovery mode then all transactions are logged in transaction log. If you can read transaction log you can in theory figure out what were the previous values of all affected rows and then recover data.

Recovery methods:

  • One method is using SQL queries similar to the one posted here for truncate or using functions like fn_dblog to read transaction log.

  • Another one is to use third party tools such as ApexSQL Log, SQL Log Rescue, ApexSQL Recover or Quest Toad

like image 34
Nath_Math Avatar answered Oct 11 '22 12:10

Nath_Math