SQL Server : Rollback without BEGIN TRANSACTION - sql

Is there a way we can rollback to previous state of the transaction using ROLLBACK without BEGIN TRANSACTION?
delete from table1;
ROLLBACK
Message:
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
Any input would be of great help.
Thanks !!!

To expand on gerrytans answer when you explicitly set IMPLICIT_TRANSACTIONS ON, you can use a ROLLBACK. See the MSDN doco related to this. Note that this isn't the default autocommit transaction mode.
This allows me to run a statement like;
SET IMPLICIT_TRANSACTIONS ON
INSERT INTO my_table (item_type, start_date_time)
VALUES ('TEST', CURRENT_TIMESTAMP)
ROLLBACK
-- Shouldn't return the 'TEST' value inserted above.
SELECT * FROM my_table ORDER BY start_date_time DESC

As SQL server error tells you -- no you can't. And many people would be curious why would you want that in the first place.
Keep in mind SQL server has an implicit transaction -- that is for DML you issue without explicit BEGIN TRAN, SQL server will start and finish a transaction for you behind the screen.
A common usage of ROLLBACK is for error handling. If somewhere in the middle of the transaction you realize you cannot proceed further due to bad user input or other reason -- then a reasonable action is to ROLLBACK to return to the starting point
The worst thing that can happen is leave your data state 'somewhere in the middle'.

You must have a BEGIN TRANSACTION before you can use the ROLLBACK command. You can't go back to the previous state.

Related

Uncommitted transaction asking every time in SQL Server 2012

I am facing issues like whenever I open SQL windows and run any SQL transaction (insert, update or delete or any modification in procedure), it asks about uncommitted transaction.
How to fix this permanently?
Sounds like you probably have SET IMPLICIT_TRANSACTIONS on.
This will open a new transaction implicitly when it encounters statements such as insert, update or delete and no transaction is open and will require an explicit commit or rollback.
Implicit transactions may unexpectedly be ON due to ANSI defaults. For details see SET ANSI_DEFAULTS (Transact-SQL).
IMPLICIT_TRANSACTIONS ON is not popular. In most cases where IMPLICIT_TRANSACTIONS is ON, it is because the choice of SET ANSI_DEFAULTS ON has been made.
You need to go into the connection properties and ensure you have not enabled implicit transactions either explicitly or implicitly.
When you use BEGIN TRANSACTION you also need to either COMMIT TRANSACTION if it has done all the work you want correctly or ROLLBACK TRANSACTION if there has been issues and you want to return to the state before the start of the transaction.
Read up on transactions here

Can i return SQL procedure before committing the transaction?

Can i use return statement in a sql transaction procedure?
Sql Procedure
ALTER PROCEDURE [dbo].[uspProcessStudentRecord]
AS
Begin Transaction
insert into dbo.Student(name,address) values('ABC','INDIA');
return;
Commit Transaction
Is it a good practice of writing return inside a Transaction?
Is it a good practice of writing return inside a Transaction?
No. In fact you will get this SQL Server error and the transaction will remain uncommitted:
Transaction count after EXECUTE indicates a mismatching number of
BEGIN and COMMIT statements. Previous count = 0, current count = 1.
When a transaction is started in a stored procedure, the best practice is to COMMIT or ROLLBACK prior to returning. Also, it's a good practice to specify SET XACT_ABORT ON in procs with explicit transactions to avoid inadvertently leaving a transaction open after a timeout.
rollback transaction will undo it.
returning it will do nothing if you didn't commit it first.
But i do not see any point of doing what you are doing now in your statement unless you are going to use a try catch or some other statement.
If you really do want to be able to commit even if the transaction is rolled back (and the only viable reason I can think of is for logging purposes) there are a couple of options open to you:
Use the Service Broker with event notifications link
Use a linked server pointing back to same DB instance without distributed transaction promotion - this will commit in a completely isolated transaction.
But please first reconsider if this is something you really need to do!

When do I have to commit?

I heard in SQL I do not have to commit every statement. Perhaps create I don't have to.
So can you answer me which Statements I have to commit?
I read, that I have to commit all transactions, but I don't know what this is and can't find it anywhere.
Thanks for your help.
Per the SQL standard, most statements that require a transaction will automatically open one.
Some database engines, such as SQL Server, will (by default) automatically commit the transaction if the statement completes successfully. See Autocommit Transactions.
Autocommit mode is the default transaction management mode of the SQL Server Database Engine. Every Transact-SQL statement is committed or rolled back when it completes
SQL Server also has an Implicit Conversions mode which will leave the transaction open until it's explicitly commited.
When operating in this second such mode (which is the default, I believe, for Oracle), or if you've explicitly created a transaction, it's up to you as a developer when to commit the transaction. It should be when you've accomplished a "complete" set of operations against the database.
If you BEGIN a transaction then you have to either ROLLBACK or COMMIT
Example:
BEGIN TRAN
--Your code
INSERT INTO
NewTable
SELECT *
FROM TABLE
COMMIT TRAN
If you do not use that, it is committed upon execution. So the follow will either fail or be committed:
INSERT INTO
NewTable
SELECT *
FROM Table
If there is an error (like there is no NewTable in the DB) the execution will raise an error and the transaction will roll back. If there is no error the transaction will be committed.

Execute Statements in a Transaction - Sql Server 2005

i need to update a database where some of the table have changed (columns have been added). I want to perform this action in a proper transaction. If the code executes without any problem then i will commit the changes otherwise i will rollback the database back to its original state.
I want to do something like this:
BEGIN TRANSACTION
...Execute some sql statements here
COMMIT TRANSACTION (When every thing goes well)
ROLLBACK TRANSACTION (When something goes wrong)
Please tell me what is the best way to do this i know there is a ##TranCount variable but dont know its exact purpose.
Thanks.
Begin Transaction
Alter Table dbo.MyTable
Add Col1 varchar(50)
If ##Error = 0
Begin
Commit Transaction
End
Else
Begin
Rollback Transaction
End
##Error gets reset after each SQL Statement so you must check it immediately after each statement has been executed to check for any errors.

Does a transaction affect all queries?

I started a transaction using BEGIN TRANSACTION in Management Studio but I forgot to ROLLBACK or COMMIT it for about 10 minutes. I freaked out and went back to ROLLBACK my changes. Did this rollback all queries that went through the server during that time or just through my user/connection?
Just your connection :-)
(Edit: rather your transaction, since the BEGIN TRANSACTION. If you did updates before the BEGIN TRANSACTION in the same session, they will of course not be rolled back)
BUT: It could have given SELECTs of other sessions the wrong answer depending on what lock types and query hints that were being used...
An example:
In one SQL Studio session, do the following:
CREATE TABLE a(a INT)
INSERT INTO a VALUES(1)
BEGIN TRANSACTION
UPDATE a
SET a = 2
SELECT *, ##TRANCOUNT
FROM a
-> You will see '2, 1' as result
Open a new session (tab in Sql studio)
Do:
SELECT *, ##TRANCOUNT
FROM a (NOLOCK)
You will see '2, 0'
Now, in first session, do
ROLLBACK TRANSACTION
SELECT *, ##TRANCOUNT
FROM a
-> transaction rolled back, and you see '1, 0'
-> a select in second session will also show '1, 0'
so: If you use (NOLOCK) hint, you can get uncommitted data as result -> which might lead to very unexpected effects :-)
Dont forget:
DROP TABLE a
when you're done ;)
It should only affect your transaction, so only things that were done in your session during that time.
You're fine. All the other queries will go through just fine.
It should roll back all queries made in the transaction, so it is more specific than your user\connection and definitely not all queries on the box.
You need to review the ACID properties of transactions. You see that there is nothing to worry about if a transaction is rolled back or committed it has no effect on the outcome of other transactions.
Your rollback affects only your transaction. The I in ACID.
However, the rows, pages or whole table you locked will affect other users if they want to use them. It depends on:
what they want to do
lock timeout
client command timeout