Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I really need to use transactions in stored procedures? [MSSQL 2005]

I'm writing a pretty straightforward e-commerce app in asp.net, do I need to use transactions in my stored procedures?

Read/Write ratio is about 9:1

like image 699
roman m Avatar asked Sep 13 '08 08:09

roman m


People also ask

Are SQL stored procedures transactional?

Yes, a stored procedure can be run inside a transaction.

Do stored procedures run in a transaction?

This is how stored procedures work by default. The stored procedure isn't wrapped within a transaction automatically. If you want the stored procedure to stop when it hits the first error you'll want to put some TRY/CATCH login in there to return in the event of a problem with command 2 for example.

Why you should not use stored procedures?

Stored procedures are difficult to unit test. With an ORM, you can mock your database code so as to be able to test your business logic quickly. With stored procedures, you have to rebuild an entire test database from scratch. Stored procedures offer no performance advantage whatsoever.


2 Answers

Many people ask - do I need transactions? Why do I need them? When to use them?

The answer is simple: use them all the time, unless you have a very good reason not to (for instance, don't use atomic transactions for "long running activities" between businesses). The default should always be yes. You are in doubt? - use transactions.

Why are transactions beneficial? They help you deal with crashes, failures, data consistency, error handling, they help you write simpler code etc. And the list of benefits will continue to grow with time.

Here is some more info from http://blogs.msdn.com/florinlazar/

like image 164
Codeslayer Avatar answered Sep 25 '22 02:09

Codeslayer


Remember in SQL Server all single statement CRUD operations are in an implicit transaction by default. You just need to turn on explict transactions (BEGIN TRAN) if you need to make multiple statements act as an atomic unit.

like image 25
Mike L Avatar answered Sep 27 '22 02:09

Mike L