Solved

Do stored procedures need transactions?

Posted on 2011-09-21
5
194 Views
Last Modified: 2012-05-12
If I want everything in a stored procedure to roll back if any part fails, does it need begin/commit transaction?

Also, if I insert into tableM and just after need the indentity value from that insert, is @@IDENTITY the correct way to get it?  @@IDENTITY will get the last indentity value on any connection so I'm not sure about using it.  But does being in a sproc or transaction make a different?
0
Comment
Question by:brettr
5 Comments
 
LVL 32

Assisted Solution

by:ewangoya
ewangoya earned 100 total points
Comment Utility

Yes, you need to use transaction begin/commit/rollback

@@IDENTITY will function the same way in a stored procedure
0
 
LVL 24

Assisted Solution

by:DBAduck - Ben Miller
DBAduck - Ben Miller earned 100 total points
Comment Utility
Just a note that I would not use @@IDENTITY as it has some Scoping problems like for triggers, etc.

Use SCOPE_IDENTITY() directly after the statement, or if you want to eliminate all scoping problems, just look up the OUTPUT clause for Inserts in BOL.
0
 
LVL 5

Expert Comment

by:AlokJain0412
Comment Utility
Yes begin tran
 and
rollback
and
Commit
 required

For better undersstanding  of Idendtity value
 (@@IDENTITY vs SCOPE_IDENTITY())  You can better understand with refer Link

http://cgaskell.wordpress.com/2006/11/15/using-identity-vs-scope_identity-and-further-implications-with-triggers/  
0
 

Author Comment

by:brettr
Comment Utility
@AlokJain0412

What is the best way to rollback?  I've seen several techniques.  Most just look for an error code and put the rollback in a conditional.
0
 
LVL 5

Accepted Solution

by:
AlokJain0412 earned 300 total points
Comment Utility
Dear this is the perfect statndard exmple of tansaction and error handling ,

1. @error return the error no of last transaction
and @error =0 means no error
 
2. If @@TRANCOUNT has a different value when a stored procedure finishes than it had when the procedure was executed, an informational error (266) occurs. This can happen in two ways:

A stored procedure is called with an @@TRANCOUNT of 1 or greater and the stored procedure executes a ROLLBACK TRANSACTION statement. @@TRANCOUNT decrements to 0 and causes an error 266 when the stored procedure completes.

A stored procedure is called with an @@TRANCOUNT of 1 or greater and the stored procedure executes a COMMIT TRANSACTION statement. @@TRANCOUNT decrements by 1 and causes an error 266 when the stored procedure completes. However, if BEGIN TRANSACTION is executed after the COMMIT TRANSACTION, the error does not occur.

------------------------

Using TRY...CATCH to Rollback a Transaction in the Face of an Error

    As you saw in earlier example, one of the downsides of the @@ERROR variable approach is that to implement Transaction; we must check this variable after each and every DML SQL statement to determine if an error occurred and, if so, to rollback the transaction. With SQL Server 2005's TRY...CATCH block, however, these types of scripts are greatly simplified.
    Lets Alter the Previous Example!

ALTER PROC usp_AccountTransaction

@AccountNum INT,

@Amount DECIMAL

AS

BEGIN

BEGIN TRY --Start the Try Block..

BEGIN TRANSACTION -- Start the transaction..

UPDATE MyChecking SET Amount = Amount - @Amount

WHERE AccountNum = @AccountNum

UPDATE MySavings SET Amount = Amount + @Amount

WHERE AccountNum = @AccountNum

COMMIT TRAN -- Transaction Success!

END TRY

BEGIN CATCH

IF @@TRANCOUNT > 0

ROLLBACK TRAN --RollBack in case of Error

-- you can Raise ERROR with RAISEERROR() Statement including the details of the exception

RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)

END CATCH

END

GO

    Just look at the simplicity and line of code than previous example!

    In the TRY block a transaction is started and the two UPDATE statements are performed. If both UPDATEs succeed, the COMMIT will be reached and the transaction committed. If, however, either one produces an error, control will be execute CATCH block where the transaction will be rolled back.

    Also, you can “re-raises” the error (using RAISERROR) so that the error information will be passed up to your .Net application from where you are calling the Stored Procedure, in case if you want to use the error information to process further steps anyhow.

    Thats it. lets Code Better!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

by Mark Wills PIVOT is a great facility and solves many an EAV (Entity - Attribute - Value) type transformation where we need the information held as data within a column to become columns in their own right. Now, in some cases that is relatively…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now