SQL Server's TRUNCATE transaction rollback operation method, servertruncate

Source: Internet
Author: User

SQL Server's TRUNCATE transaction rollback operation method, servertruncate

We generally think that TRUNCATE is an operation that cannot be rolled back. It will delete all data in the table and reset the Identity column.

If you perform the TRUNCATE operation in the transaction, you can roll back. Otherwise, it will not recover data from the log file. It does not record the deleted data in the log file. It only records the unit allocation on the data page in the log.

The following example explains the above.

Copy codeThe Code is as follows: USE temp_test_database
GO
-- Create a temporary table
Create table TruncateTabel (id int)
Insert into TruncateTabel (ID)
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
GO

Copy codeThe Code is as follows: -- check the inserted data
SELECT * FROM TruncateTabel


Start transaction execution

Copy codeThe Code is as follows:
-- Start transaction
BEGIN TRAN
Truncate table TruncateTabel
GO
-- Check TruncateTable before rollback
SELECT * FROM TruncateTabel
GO

F5 execution,

Execute rollback transactions

Copy codeThe Code is as follows: -- roll back the transaction
ROLLBACK TRAN
GO

Check TruncateTable again

Copy codeThe Code is as follows: -- check TruncateTable again after rollback
SELECT * FROM TruncateTabel
GO

F5 execution,

To sum up, transactions can roll back the TRUNCATE operation.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.