Solved

Do stored procedures need transactions?

Posted on 2011-09-21
5
241 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 32

Assisted Solution

by:Ephraim Wangoya
Ephraim Wangoya 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
spx for moving values to new table 5 75
create insert script based on records in a table 4 28
Addition to SQL for dynamic fields 6 56
tempdb log keep growing 7 44
I am showing a way to read/import the excel data in table using SQL server 2005... Suppose there is an Excel file "Book1" at location "C:\temp" with column "First Name" and "Last Name". Now to import this Excel data into the table, we will use…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

749 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