Solved

Do stored procedures need transactions?

Posted on 2011-09-21
5
208 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
ID: 36577623

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
ID: 36577857
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
ID: 36578379
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
ID: 36581263
@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
ID: 36585116
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Incremental load example 2 52
SQL Encryption question 2 50
Why do I get extra rows when I do inner join? 12 38
Restrict result set 1 35
This article will describe one method to parse a delimited string into a table of data.   Why would I do that you ask?  Let's say that you need to pass multiple parameters into a stored procedure to search for.  For our sake, we'll say that we wa…
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.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

920 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

15 Experts available now in Live!

Get 1:1 Help Now