Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come recuperare i dati dalla tabella troncata

Se utilizzi TRANSACTIONS nel tuo codice, TRUNCATE può essere annullato. Se non viene utilizzata alcuna transazione e viene eseguito il commit dell'operazione TRUNCATE, non è possibile recuperarla dal file di registro. TRUNCATE è un'operazione DDL e non è registrato nel file di registro.

DELETE e TRUNCATE possono essere entrambi annullati quando sono circondati da TRANSACTION se la sessione corrente non è chiusa. Se TRUNCATE è scritto nell'editor di query circondato da TRANSACTION e se la sessione è chiusa, non è possibile eseguire il rollback ma DELETE può essere ripristinato.

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