Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: how transactions work

In SQL Server, how many transactions will this produce?

DECLARE @deleted BIGINT
SET @deleted = 100000
WHILE @deleted = 100000
BEGIN
DELETE TOP(100000) FROM MYTABLE WITH (ROWLOCK)
where Col1 = 7048 and COL2 = 39727 and Col3 = 0
SET @deleted = (SELECT @@ROWCOUNT)
END

If I cancel after running this for 10 minutes will it need to roll back?

Would adding a being transaction and end transaction fix this if I don't want it to rollback past one iteration after a cancel?

Would it make any difference if I put it in a stored procedure?

like image 292
MS SQL Server Avatar asked Jan 28 '26 06:01

MS SQL Server


2 Answers

When you don't have the BEGIN TRANSACTION and COMMIT, you have implied transactions. And, each DELETE will be a separate transaction. So, if you cancel the script, it will rollback the current command. But, all previous DELETE steps are already committed.

If you add a BEGIN TRANSACTION before your code and a COMMIT after your code, then you get a single transaction. If you cancel the query, you leave an open transaction, where there is not commit or rollback. In this case, you must submit a ROLLBACK command to start the rollback process.

like image 188
bobs Avatar answered Jan 30 '26 00:01

bobs


It will be an implicit transaction. remember ACID? everything in SQL Server is a transaction either implicit or explicit otherwise you wouldn't be able to guarantee ACID

like image 30
SQLMenace Avatar answered Jan 30 '26 00:01

SQLMenace