Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT and DELETE in the same transaction?

I have a Temp_Table with some data. Based on the data in the Temp_Table, I will delete the related rows from other tables, and after that, insert all data from the Temp-table to table1. Like the example below.

In what way could I place a lock on Server2.Table1 (exclusive I supose) and run both the Delete and Insert statements before letting go of that lock? I don't want anyone to read or write to Table1 while I am doing my Delete / Inserts. Note that the Delete must be run before the Insert statement.

Is there a way is SSIS to do this? Or can I use Begin transaction in the beginning and commit transaction after the statements? I fear that both the Delete and Insert will run simultaneously while in the same transaction..

DELETE Table1 
FROM Table1 t1
    INNER JOIN (    
       SELECT Column2 FROM Temp_Table
       GROUP BY Column2
    ) t2 ON t1.Column2 = t2.Column2

INSERT INTO Table1
SELECT (Column1, Column2...)
FROM Temp_Table
like image 618
Andreas Avatar asked Aug 22 '16 19:08

Andreas


2 Answers

You can use OUTPUT clause in delete to insert into temp table

DELETE FROM dbo.table1  
OUTPUT DELETED.* INTO @MyTable  --or temp table   
WHERE id = 10

In this case both operation will be in single transaction..

like image 137
Kannan Kandasamy Avatar answered Oct 12 '22 13:10

Kannan Kandasamy


SteveRs comment was correct, the Insert and Delete statements within a transaction didn't run simultaneously. After some testing on a non-production database, I ended up with the following:

BEGIN TRY
    BEGIN TRAN T1;

DELETE Table1 
FROM Table1 t1
    INNER JOIN (    
       SELECT Column2 FROM Temp_Table
       GROUP BY Column2
    ) t2 ON t1.Column2 = t2.Column2

INSERT INTO Table1 (Column 1, Column2...)
SELECT (Column1, Column2...)
FROM Temp_Table

COMMIT TRAN T1;

END TRY
BEGIN CATCH
        ROLLBACK TRAN T1;
END CATCH

The Delete statement is executed first, then the Insert statement. And the Exclusive lock will not be released between the statements.

like image 43
Andreas Avatar answered Oct 12 '22 13:10

Andreas