Transaction is not performed although commit at end? - sql

I have a simple question. When I start a transaction with BEGIN TRAN and in the middle I write some statements and at the end is write COMMIT TRAN, whats happens if one statement fails? Will the transaction still be committed and I need to check after every statement if ##ERROR <> 0? And what happens if I write at the end ROLLBACK TRAN? Will the transaction rollbacked also when all statements worked properly? I am a bit confused :/

If you use COMMIT TRAN your query will be executed only if there are no errors while ROLLBACK TRAN is used to check if the query is working properly or not, it will definitely rollback even if there is no issue with the query.

Related

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!

Cannot roll back subtransaction. No transaction or savepoint of that name was found

i have a loop while in sql which do something as it
begin tran one
do some inserts in others tables
--start loop
begin tran two
--do something
begin try
--if something fail then a trigger does rollback and this return a error (and this goes to catch), then don't i need do the rollbak in catch? this could not be dissable because this is working on production
--something finished ok
commit tran two
end try
begin catch
rollback tran two
end catch
--finished loop
commit
----------
i got this error
Uncommittable transaction is detected at the end of the batch. The
transaction is rolled back.
begin tran one
begin tran two
rollback tran two
doing this code i get this:
Cannot roll back two. No transaction or savepoint of that name was found.
I only want the subquery to rollback the second loop and continue with others records.
Operator rollback rolls back all transaction, for roll back only second loop you you must use savepoints:
begin tran one
-- do some inserts in others tables
--start loop
save tran two -- begin tran two
--do something
begin try
update product set id = 1 --if something fail then a trigger does rollback and this return a error (and this goes to catch), then don't i need do the rollbak in catch? this could not be dissable because this is working on production
--something finished ok
commit tran two
end try
begin catch
rollback tran two
end catch
--finished loop
commit
trigger example:
create table product (id int)
GO
create trigger product_trigger on product for update
as
set xact_abort off
if (select count(*) from inserted i join product p on i.id=p.id)=0 begin
if (##trancount>0) begin
/* rollback */
raiserror('product does not exist', 16, 1)
end
end
In my case, was my code was calling, thru an EF DbContext method, a SQL Server stored procedure, which contained a non-nested transaction.
Since, as #NotMe has already pointed-out, that "there is no such as a nested transaction in SQL Server", I began wondering whether my process was really transaction-nestingless.
Suspecting, that my DbContext had some guilt, I started checking on DbContext options, until DbContext.Configuration.EnsureTransactionsForFunctionsAndCommands = True caught my attention.
So, as soon as I changed it value to True, everything worked successfully.
MyDbContext.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
What happened?
Well, in my opinion, EF's ObjectContext.ExecuteFunction method was managing its own outer transaction as a wrapper to my stored procedure's inner transaction, so, when my stored procedure's ROLLBACK TRAN was hit, there was no pending transaction when EF's COMMIT/ROLLBACK code was hit.
Oddly enough, while gathering some references on EnsureTransactionsForFunctionsAndCommands property, I found that this default behaviour is due to one of the worst (in my opinion) EF team's decision ever, since it collides diretly with every ROLLBACK TRAN inside a T-SQL script.
For further details on EF, check insightfull SO's QA at EF6 wraps every single stored procedure call in its own transaction. How to prevent this?
Basically, everyone should check ##trancount > 0 before issuing a ROLLBACK command, whether named or not, specially inside stored procedure.
CREATE PROCEDURE Proc1 AS
BEGIN
BEGIN TRAN
EXEC Proc2
IF(##trancount > 0)
COMMIT TRAN
END
CREATE PROCEDURE Proc2 AS
BEGIN
BEGIN TRAN
ROLLBACK TRAN
END
For better awareness about Microsoft SQL Server's nested transactions, I would suggest reading the following article
Be careful using ROLLBACK on nested transaction in SQL Server!
Hope it helps someone :-)

SQL Server : Rollback without BEGIN TRANSACTION

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.

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.

Executing a stored procedure inside BEGIN/END TRANSACTION

If I create a Stored Procedure in SQL and call it (EXEC spStoredProcedure) within the BEGIN/END TRANSACTION, does this stored procedure also fall into the transaction?
I didn't know if it worked like try/catches in C#.
Yes, everything that you do between the Begin Transaction and Commit (or Rollback) is part of the transaction.
Sounds great, thanks a bunch. I ended up doing something like this (because I'm on 05)
BEGIN TRY
BEGIN TRANSACTION
DO SOMETHING
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
END CATCH
I believe in MS SQL Server the stored procedure execution would happen within the transaction, but be very careful with this. If you have nested transactions (ie, transaction outside of the stored procedure and a different transaction inside the stored procedure), a rollback will affect ALL of the transactions, not just the nearest enclosing transaction.
As Chris mentioned, you should be careful about rolling the transaction back.
Specifically this:
IF ##TRANCOUNT > 0 ROLLBACK
is not always what you want. You could do something like this
IF(##TRANCOUNT = 1) ROLLBACK TRAN
ELSE IF(##TRANCOUNT > 1) COMMIT TRAN
RETURN #error
This way, the calling proc can inspect the return value from the stored procedure and determine if it wants to commit anyways or continue to bubble up the error.
The reason is that 'COMMIT' will just decrement your transaction counter. Once it decrements the transaction counter to zero, then an actual commit will occur.
As Chris and James mentioned, you need to be careful when dealing with nested transactions.
There is a set a very good articles on the subject of transactions written by Don Peterson on SQL Server Central , I would recommend having a read of those:
Here there are:
part 1
part 2
part 3
Yes, all nested stored procedure calls are included in the scope of the transaction. If you are using SQL Server 2005 or greater, you can use Try...Catch as well. Here is more detail on that.
#Chris, I did not know that.
When googling for more info, I came across this - you can set 'savepoints', which can be rolled back to without rolling back the whole transaction.
Could be useful in this situation.