Does a T-SQL transaction get rolled back if cancelled? - sql

In haste, I stupidly ran a statement to update a table without qualifying it with a where statement. So it started to update all records in the table.
I immediately noticed the error and hit the 'Cancel Execution" button in SQL Server Management Studio, but it took a minute to stop running.
So my question is, did it roll back the changes or were they made until it was told to stop?
I can't tell which records were updated just by looking at them. I'd have to restore the table if it did make any changes.
Thanks.
I wanted to run:
Update tableA
set newdate = '2019-01-01'
where account = 'abc'
but instead I ran:
Update tableA
set newdate = '2019-01-01'
The database is a transactional type database.

SQL Server has the default transaction behaviour by default. That means that each sentence you run in the query editor is like:
BEGIN TRANSACTION
<YOUR COMMAND>
COMMIT TRANSACTION
So, if you have cancelled before finished, the transaction should be rolled back.

If the query hasn't finished before being cancelled then yes, it was rolled back. Either whole update was executed or nothing was changed.

Related

What will happen if I execute rollback statement on simple select query

I executed a simple SQL performance query to retrieve the sessions running currently in the database in Oracle sql developer.
But accidentally my cursor clicked on the roll back icon and it got rolled back.
Could you please tell me What happens to the entire database after this?
Rolling back a select does nothing as long as you didn't make changes to the database without committing the transaction.
In oracle clients when you run a query that modifies the database, the query is first run. Another step is then needed to commit the transaction.
MS SQL Server has a similar concept where you can do safe transactions like
begin tran
delete from table where val > 5
rollback{commit}
This allows you to look at the number of records your SQL statement have done prior to committing the transaction. If you want you can choose to rollback or commit your transaction.
What exactly did you roll back? That "simple SQL performance query", or "sessions running currently in the database in Oracle SQL Developer"?
If former, nothing happened, SELECT didn't do any changes anyway. If it were SELECT ... FOR UPDATE, lock would have been released.
If latter, then any changes you did in the database since previous COMMIT were rolled back (as you didn't roll back to a savepoint), so - nothing happened either.
What happens to the entire database after this?
It returned to state it was in earlier, as if you didn't touch anything at all.

How can I ensure a series data modify operation all performed?

I have a series data modify operation to do,such as
1. update table_a set value=1 where id=1
2. update table_b set value=2 where id=1
3. update table_c set value=3 where id=1
and I want to ensure this three operation must all complete,I know using transaction can guarantee all performed or none performed.But my point is must make these three all performed.when first sql performed,the app instance may crashed and the other two are missed.
Note this is a ditributed enviroment,may be another app instance can take over the unfinished SQL,but how can I do it?
Can I use a stored procedure,the app instance only fire the stored procedure,and database finsh all the sql?
If when performing transaction,the app instance suddenly crashes,will it leads to a dead lock?
Deadlocks are not crashed requests which fail before the end of the execution. If your request crashes into a transaction, it won't lead to a deadlock.
It is always better to use stored procedures but this won't help you for this specific case.
What I would suggest is inded the use of a transaction with a try catch to rollback the transaction in case of failure.
Something like that :
BEGIN TRY -- start of try
BEGIN TRANSACTION; -- start of transaction
update table_a set value=1 where id=1
update table_b set value=2 where id=1
update table_c set value=3 where id=1
COMMIT TRANSACTION; -- everything went ok we commit
BEGIN CATCH -- an error happened we rollback
PRINT N'Unexpected error';
ROLLBACK TRANSACTION;
END CATCH
You can check more complete examples here
If an app is performing a transaction on a database server, and the app crashes (abruptly disconnects from the database) before committing the transaction, the database server rolls back the transaction. The disconnection does not leave the database in an unusable (potentially deadlocked) state.
So your database contents won't reflect any of your three UPDATE operations when your app crashes during your transaction. It will just lose the transaction in progress.
How to handle this potential failure mode?
Reduce the probability of a crash during a transaction. Try to avoid doing stuff in your app that could make it crash while your transaction is in process. For example, if you get data from some other server or device, get it all before you begin your transaction. This solution is usually good enough for production apps.
Rig up some sort of way for your app, upon restarting, to find out the most recent successful transaction. One good way? Add a column like this to one of your tables: (this is a MySQL thing.)
last_update_timestamp TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
This causes every UPDATE operation on each column to -- automatically -- put NOW() into the last_update_timestamp column. Then, when your crashed app restarts you can do
SELECT MAX(last_update_timestamp) FROM table
and you'll know when the most recent successful update occurred. This automatic update also gets rolled back if a transaction is rolled back. If you know when the last successful update occurred, your app may be able to redo the one that was rolled back by the crash.
If you choose to build a redo-transaction capability, be sure to build it so you can test it! if (testingAppCrash) crashNow = 1 / 0; might do the trick in your app.

Does stopping query with a rollback guarantee a rollback

Say I have a query like this:
BEGIN Transaction
UPDATE Person SET Field=1
Rollback
There are one hundred million people. I stopped the query after twenty minutes. Will SQL Server rollback the records updated?
A single update will not update some rows. It will either update all or 0.
So, if you cancel the query, nothing will be updated.
This is atomicity database systems which SQL Server follows.
In other words, you don't have to do that rollback at the end, nothing was committed anyway.
When you cancel a query, it will still hold locks until everything is rolled back so no need to panic.
You could test it yourself, execute the long query, cancel it and you will notice that it takes a while before the process really end.
While the update statement will not complete, the transaction will still be open, so make sure you rollback manually or close out the window to kill the transaction. You can test this by including two statements in your transaction, where the first one finishes and you cancel while it's running the second - you can still commit the transaction after stopping it, and then get the first half of your results.
BEGIN Transaction
UPDATE Person SET Field=1 WHERE Id = 1
UPDATE Person SET Field=1
Rollback
If you start this, give it enough time for the first line to finish, hit the Stop button in SSMS, then execute commit transaction, you'll see that the first change did get applied. Since you obviously don't want part of a transaction to succeed, I'd just kill the whole window after you've stopped it so you can be sure everything's rolled back.
Since you have opened the Transaction, Stoping the Query manually does not completes the transaction, This transaction will still be open and all the subsequent requests to this table will be blocked.
You can do any one of following options
Kill the Connection using the command KILL SPID (SPID is the process ID of your connection)
Note: This will auto rollback the changes you made, you can monitor the rollback status with command KILL SPID WITH STATUSONLY (After killing)
run the ROLLBACK command manually
** SPID is your request id, you can find it from sys.sysprocesses table/ you can also find it on Management Studio query Window the number which is within brackets / also you can find it at bottom right corner of your management studio beside the login name.
Example SQLQuery2.sql... (161) -- 161 is your spid.

How to return back in SQL statement

I have run SQL server command (update command).
the command has been performed successfully and the table has been updated
is there any way to take back in that command ?
note: no backup taken
If you had originally asked the question how do I do an UPDATE with the possibility of ROLLBACK I would tell you you should do your ad-hoc updates like this.
BEGIN TRANSACTION
UPDATE blah
SET value = newvalue
WHERE condition = someothervalue
--COMMIT TRANSACTION
Then if the results are as expected run the COMMIT TRANSACTION. If they are not than you could do a ROLLBACK TRANSACTION. However since you already did the updates and have no backups or recovery plan you are pretty much out of luck.
After you have already executed an update command the only way back would be via restoring a backup.
Something I do when writing any modification scripts is to wrap the command in a transaction and then either run a rollback or a commit depending on if the query performed as suspected.
Example:
--start the transaction only execute the first three lines, this leaves the transaction open
BEGIN TRANSACTION
UPDATE TABLEA
SET COL1 = "newValue"
--examine data and based on the results run one of these two lines
ROLLBACK TRANSACTION
COMMIT TRANSACTION

MS SQL 2005- Rollback Update query

I'm using MS SQL Server 2005 enterprise edition. I executed an update query to get affect a record in a row and a column.
update HS_SM_USERACCOUNT
set ACCOUNTPOLICYTYPE=1
where EMP_NUMBER='000540' and USERID='03510410#'
Earlier the column called ACCOUNTPOLICYTYPE is holding value 1 for that particular condition in WHERE clause. Now I want to get the previous state without executing Update Query again.
Will ROLLBACK help me? Please help me on this.
No. It's changed. If you want to know what it was, restore from backup
Unless you executed the above query within the scope of a TRANSACTION - i.e. within BEGIN TRAN / COMMIT / ROLLBACK TRAN block, the ROLLBACK command is going to be of no use.
There is nothing you can do to get back the state that you updated with the above statement in such a situation except RESTORE an OLD backup of that table data