Use transactions for select statements?

Sql ServerTsqlStored Procedures

Sql Server Problem Overview


I don't use Stored procedures very often and was wondering if it made sense to wrap my select queries in a transaction.

My procedure has three simple select queries, two of which use the returned value of the first.

Sql Server Solutions


Solution 1 - Sql Server

In a highly concurrent application it could (theoretically) happen that data you've read in the first select is modified before the other selects are executed.

If that is a situation that could occur in your application you should use a transaction to wrap your selects. Make sure you pick the correct isolation level though, not all transaction types guarantee consistent reads.

Update : You may also find this article on concurrent update/insert solutions (aka upsert) interesting. It puts several common methods of upsert to the test to see what method actually guarantees data is not modified between a select and the next statement. The results are, well, shocking I'd say.

Solution 2 - Sql Server

Transactions are usually used when you have CREATE, UPDATE or DELETE statements and you want to have the atomic behavior, that is, Either commit everything or commit nothing.

However, you could use a transaction for READ select statements to:
Make sure nobody else could update the table of interest while the bunch of your select query is executing.

Have a look at this msdn post.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchoboView Question on Stackoverflow
Solution 1 - Sql ServerMarnix van ValenView Answer on Stackoverflow
Solution 2 - Sql ServerFIre PandaView Answer on Stackoverflow