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
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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With