iSnare.com - Free Content Articles Directory
Authors Contents [Advanced Search][Add OpenSearch][Job Search]
Distribute your articles to thousands of article sites for only $2 and below! Read more...

Index  Computers and Technology
 

Record Locking In Sql Server

 
[ Contact the Author] [ Send to a Friend] [ Article Publisher] [Make PDF] [ Print] [ Bookmark & Share]
 
Read our Terms of Service before reprinting this article. The submitter specified above has claimed the rights to this article.
Kalpesh

In a multi-user environment, there are two models for updating data in a database: optimistic concurrency and pessimistic concurrency.

Pessimistic concurrency involves locking the data at the database when you read it. You essentially lock the database record and don't allow anyone to touch it until you are done modifying and saving it back to the database. Here you have 100% assurance that nobody will modify the record and while you check it have it checked out, out. aAnother person will have to wait until you have made the your changes.

By default, SQL Server controls lock escalation, but you can control it yourself by using lock optimizer hints. Here are some lock escalation hints you may want to consider:

· ROWLOCK This hint guides tells SQL Server to use row-level locking instead of page locks for INSERTS. By default, SQL Server may perform as a page-level lock instead of a less intrusive row-level lock when inserting data. By using this hint, you can guide tell SQL Server to always start out using row-level locking. But, this hint does not prevent lock escalation if the number of locks exceeds SQL Server's lock threshold.

· SERIALIZABLE (equivalent to HOLDLOCK) applies only to the table specified and only for the duration of the transaction, and it will hold a shared lock for this duration instead of releasing it as soon as the required table, data page, row or data is no longer required.

· TABLOCK specifies that a table lock to be used instead of a page or row level lock. This lock will be remained held until the end of the statement.

· TABLOCKX specifies that an exclusive lock will be applied held on the table until the end of the statement or transaction, and will prevent others from reading or updating the table.

· UPDLOCK specifies that update locks will be used instead of shared locks, and will hold the locks until the end of the statement or transaction.

· XLOCK specifies that an exclusive lock be used and kept activated held until the end of the end of the transaction on all data being processed by the statement. The granularity of XLOCK will be adjusted if it is used with the PAGLOCK or TABLOCK hints.

SQL Server 7.0 and SQL Server 2000 Lock Escalation Options

You can override how SQL Server performs locking on a table by using the SP_INDEXOPTION command. Below is an example of code you can run to guide tell SQL Server to use page locking, not row locks, for a specific table:

SP_INDEXOPTION 'INDEX_NAME', 'ALLOWPAGELOCKS', TRUE

When FALSE, page locks are not used. Access to the specified indexes is obtained using row- and table-level locks only.

SP_INDEXOPTION 'INDEX_NAME', 'ALLOWROWLOCKS', TRUE

When FALSE, row locks are not used, . aAccess to the specified indexes is obtained using page- and table-level locks only.

SQL Server 2000 Lock Escalation Options

SP_INDEXOPTION 'INDEX_NAME', 'DISALLOWPAGELOCKS', TRUE

When TRUE, page locks are not used,. aAccess to the specified indexes is obtained using row- and table-level locks, only.

SP_INDEXOPTION 'INDEX_NAME', 'ALLOWROWLOCKS', TRUE

When TRUE, row locks are not used., aAccess to the specified indexes is obtained using page- and table-level locks, only.

When these commands are used, they affect all queries that eaffect these indexes. This command should not be used unless you know, positively, that they always produce the results you desire.

Important

The SQL Server query optimizer automatically makes the correct determination. It is recommended that you do not override the choices the optimizer makes. Disallowing a locking level can affect the concurrency for a table or index adversely. For example, specifying only table-level locks on a large table accessed heavily by many users can affect performance significantly. Users must wait for the table-level lock to be released before accessing the table.

Optimistic concurrency means you read the database record, but don't lock it. Anyone can read and modify the record at anytime and you will take your chances that the record is not modified by someone else before you have a chance to modify and save it. As a developer, the burden is on you to check for changes in the original data (collisions) and act accordingly based on any errors that may occur during the updating e process..

With optimistic concurrency, the application has to check for changes to the original record to avoid overwriting changes. There is no guarantee that the original record has not been changed, because no lock has been placed on that data at its source - the database. Hence, there is the real possibility of losing changes made by another person.

Optimistic Concurrency Strategies

If you are in a performance state-of-mind, there are chances of your chosingchances are you will go with optimistic concurrency. Optimistic concurrency frees up database resources as quickly as possible so that other users and processes can act upon that data as soon as possible.

There are four popular strategies to deal ing with optimistic concurrency:

1. Do Nothing.

2. Check for changes to all fields during update.

3. Check for changes tof modified fields during update.

4. Check for changes to timestamp (row version) during update.

All of these strategies have to deal with the shaping of the Update T-SQL Command sent to the database during the updating of the data. The examples below are not very detailed on purpose and assume a basic understanding of ADO.NET.

Optimistic Concurrency on Update Strategy #1 - Do Nothing

The simplest strategy for dealing with concurrency issues during the updating of data is to do nothing.

The update command will not check for any changes in the data, only specify the primary key of the record to be changed. If someone else changed the data, those changes will more than likely be overwritten:

Update Product

Set

Name = @Name

Where

ID = @ID

One would hope that this means either 1) the application is a single-user application, or 2) the chance of multi-user update collisions is very unlikely and the repercussions of overwriting data is negligible.

Optimistic Concurrency on Update Strategy #2 - Check All Fields

With this strategy, the update command will check that all fields in the row (usually minus BLOB fields) are equal to their original values when performing the update to assure no changes have been made to the original record. A check of the return value of the ExecuteNonQuery Command will indicatetell you if the update actually took place. The return value of the ExecuteNonQuery Command is typically the number of rows affected by the query.

Update Product 

Set

Name = @Name,

Where

ID = @ID

AND

Name = @OriginalName

AND

Price = @OriginalPrice

This is essentially what CommandBuilder creates when using DataSets and is a strategy that doesn't want to see any changes to the data.

Optimistic Concurrency on Update Strategy #3 - Check Only Changed Fields

Rather than checking all fields in the row to make sure they match their original value, this strategy checks only those fields whichthat are being updated in the command.

Update Product

Set

Name = @Name

Where

ID = @ID

AND

Name = @OriginalName

This strategy only cares that it is not overwriting any data and could care less thant other fields in the record may have been changed. This could create an interesting combination of data in the row.

Optimistic Concurrency on Update Strategy #4 - Implement Timestamp

SQL Server has a timestamp ( alias rowversion ) field that is modified every time a change is made to a record that contains such a field. Therefore, if you add such a field to a table you only have to verify the timestamp record contains the same original value to be assured none of the fields have been changed in the record.

Update Product

Set

Name = @Name

Where

ID = @ID

AND

TimestampID = @TimestampID

This is the same as Strategy #2 above without the need for checking all fields.

Optimistic concurrency has a performance component to it that suggests a higher performing ASP.NET website.

There are other methods of achieving optimistic concurrency, but I think the ones above are the most popular. A developer needs to look at the application itself to determine which strategy makes sense. The DataSet, Command Builder, and DataAdapter typically handle this stuff for you using Strategy #2. However, if you work with objects instead of DataSets, you need to handle concurrency issues yourself.

Important NoticeDISCLAIMER: All information, content, and data in this article are sole opinions and/or findings of the individual user or organization that registered and submitted this article at Isnare.com without any fee. The article is strictly for educational or entertainment purposes only and should not be used in any way, implemented or applied without consultation from a professional. We at Isnare.com do not, in anyway, contribute or include our own findings, facts and opinions in any articles presented in this site. Publishing this article does not constitute Isnare.com's support or sponsorship for this article. Isnare.com is an article publishing service. Please read our Terms of Service for more information.

By Kalpesh Bakotiya Kalpesh Bakotiya is working as a Programmer at Semaphore Infotech Pvt. Ltd, India. You can contact on email: kalpesh@semaphore-software.com.http://www.semaphore-software.com
Article Tags: lock [See Dictionary], locks [See Dictionary], strategy [See Dictionary]
Got a question about this article? Ask the community!
Article published on April 16, 2008 at Isnare.com
 
Rate [Ratings: 0 / 5] [Votes: 1]

Reverse Cell Phone Lookup - Did You See a Number on Your Spouse's Cell You Did Not Recognize?
Submitted by: J Williams-Foster

Reverse cell phone lookup services can provide information about phone number owners for a myriad of reasons, one reason that's not always considered is in the area of love...

How to Dispose of a Multifunction Printer
Submitted by: Derek Rogers

As with most electrical equipment, your printer is full of plastics, components and potentially hazardous materials...

The Time For Buying a GPS System is Now
Submitted by: Jerbob Johnsen

Whether you are trying to decide on an auto GPS systems to window shop or purchase GPS autos system, you have definitely now have many choices compared to a few years ago...

Top 5 Camcorders - Which One to Pick?
Submitted by: Roberto Sedycias

Purchasing camcorders leads the buyer to view a wide range of choices; however, looking for the appropriate choice depends on the need of the buyer and budget...

Camcorder Recording Methods and Technology
Submitted by: Allen Roberts

Over the years, camcorders have evolved from tape (which has spanned many decades), to DVD, and more recently to Harddrives(HDD) and Flash Memory...

Valuing Your Entertainment With the LED LCD TV
Submitted by: RahXephon NeO

If you are looking into the latest technology for entertainment, then considering a LED LCD TV may be the best alternative...

How to Select a Digital Camera For Personal Needs
Submitted by: Roberto Sedycias

It is not necessarily that crucial to rely on the brand name when attempting to select the best digital camera...

Problems and Positives With Gps Cell Phones
Submitted by: Roberto Sedycias

GPS stands for Global Positioning System This can be a very valuable tool when traveling, or simply when trying to locate something in the local area without making unnecessary stops or getting lost...

Five Reasons to Choose Cold Lamination
Submitted by: Jeff McRitchie

A lot of people, when they think about laminating machines picture huge roll laminators such as you might see in a school or business, or maybe the little pouch unit that created their name badge...

GBC 3230ST Electric Hole Punch and Stapler
Submitted by: Jeff McRitchie

Two of the gadgets that every office needs are a hole punch and a stapler Can you imagine office life without a stapler...

Five Reasons Your School Should Have Fastback Binding
Submitted by: Jeff McRitchie

Powis Parker's Fastback binding system offers you a great way to show off the work of your students, print your own yearbooks, protect the books your library already owns, or to create new books from downloaded material...

Four Reasons to Always Use a Carrier With Your Pouch Laminator
Submitted by: Jeff McRitchie

There was a time when it was impossible to consider pouch lamination without the use of a pouch carrier...

Frequently Asked Questions About Copier Tabs
Submitted by: Jeff McRitchie

If you've ever wondered what copier tabs are, you're reading the right article This FAQ will answer your questions about copier tabs and let you know what they're used for, how to use them, and what kinds of copier tabs are available for your copier...

Nokia 7510 Supernova Mobile Phone Review - The Ultimate Fun But Affordable Phone
Submitted by: Carlson Osbourne

The Supernova series that Nokia has released over the past few years has been met with a variety of reactions from mobile phone reviewers, with the most prevalent feeling being one of disappointment...

What to do if Your Computer Printer Toner Runs Low
Submitted by: Adriana N

For most people, a computer has become a necessary part of their daily lives Whether it is for work or personal use, we often have to print out a number of documents on a daily basis...

Isnare.com Footer Divider

© 2004-2009. Isnare Free Articles - An Isnare Online Technologies Free Articles Project. All Rights Reserved.   Privacy Policy