Saturday, September 3, 2011

Lock Table command in Sybase ASE?

There are basically two types of locks which we can have on a Sybase ASE table namely the -
  1. Shared Lock and
  2. Exclusive Lock
The shared lock is a lock which when taken on a table then the other processes can also aquire a share lock on the same table for reading the data. Basically this type of lock is taken when performing a select and is done automatically by the Sybase ASE server just before reading the data. Once a shared lock has been taken on a table no other process can have an exclusive lock on the table as the shared and exclusive locks are incompatible so the process wanting to take an exclusive lock will need to wait until the read operations have been performed.

Exclusive lock as the name suggests require a single access to the table with no other process able to read or modify the data present in the table at the same time. This is done because when a process requires an exclusive lock on a table then the process wants to update the data on the table which will take sometime and until then if some other process tries to read the data from the table then it might view inconsistent data which wont be preferrable.

Usually, exclusive lock is taken by a process on data modifications automatically and shared lock is taken automatically by the Sybase ASE server for a process just before reading the data from the table, however if we want we can specifically suggest to Sybase ASE server that we want to have an exlusive lock on the table in a transaction. The lock table command syntax to do so is as follows -

lock table <<Table Name>> in <<share|exclusive>> mode {optional} with <<nowait| wait time in sec>>

The above syntax will help us have a shared (share) or exclusive (exclusive) lock on the table.

The above syntax comes with an optional with clause to specify the time the process needs to wait in case the lock cannot be acquired immediately. In case we do not want to wait we can use the nowait option.

Remember, we can acquire locks on tables only within the transactions so we need to have lock statements between begin and commit/rollback transaction blocks.

Also, a lock gets removed once the transaction either gets rollbacked or committed and hence there is no seperate command to remove lock on a table.

No comments:

Post a Comment