Bulk update locks In addition to choosing the type of lock, the Lock Manager in SQL Server 2008 automati-cally adjusts the granularity of the locks for example, row, page, table, based o
Trang 1end as object,
convert(varchar(12), resource_type) as resrc_type,
convert(varchar(12), request_type) as req_type,
convert(char(1), request_mode) as mode,
convert(varchar(8), request_status) as status
from sys.dm_tran_locks
order by request_session_id, 3 desc
go
spid db_name object resrc_type req_type mode status
-52 msdb 0 DATABASE LOCK S GRANT
55 bigpubs2008 titles OBJECT LOCK I GRANT
55 bigpubs2008 sales_qty_rollup OBJECT LOCK X GRANT
55 bigpubs2008 sales OBJECT LOCK X GRANT
55 bigpubs2008 679707671068672 PAGE LOCK I GRANT
55 bigpubs2008 679707671068672 KEY LOCK X GRANT
55 bigpubs2008 398232694358016 KEY LOCK X GRANT
55 bigpubs2008 398232694358016 PAGE LOCK I GRANT
55 bigpubs2008 0 DATABASE LOCK S GRANT
56 msdb 0 DATABASE LOCK S GRANT
58 bigpubs2008 sales OBJECT LOCK I WAIT
58 bigpubs2008 0 DATABASE LOCK S GRANT
Note that the query in Listing 37.1 contains a CASEexpression for displaying the object
name If the resource type is OBJECTand the database ID of the locked resource is the same
as the current database context, it returns the object name; otherwise, it returns the object
ID because the object_name()function operates only in the current database context
TIP
To save yourself the trouble of having to type in the query listed in Listing 37.1, or
hav-ing to read it in from a file each time you want to run it, you might want to consider
cre-ating your own stored procedure or view that invokes this query
NOTE
In SQL Server 2005, you could monitor lock activity via the Activity Monitor in SQL
Server Management Studio (SSMS) If you’re looking for this tool in SQL Server 2008,
you won’t find it For some reason, this feature was removed from SSMS in SQL Server
2008 The only locking information provided by the SSMS Activity Monitor in SQL
Server 2008 is the indication of lock blocking and wait time provided by the Process
Monitor and the Lock Waits information provided by the Resource Waits Monitor There
is no GUI-based lock monitoring tool provided with SQL Server 2008 to display the
spe-cific locks being held by processes or the locks being held on objects as there was in
SQL Server 2005
Trang 21355 Monitoring Lock Activity in SQL Server
Viewing Locking Activity with SQL Server Profiler
Another tool to help you monitor locking activity in SQL Server 2008 is SQL Server
Profiler SQL Server Profiler provides a number of lock events that you can capture in a
trace The trace information can be viewed in real-time or saved to a file or database table
for further analysis at a later date Saving the information to a table allows you to run
different reports on the information to help in the analysis
NOTE
This chapter provides only a brief overview of how to capture and view locking
informa-tion using SQL Server Profiler For more informainforma-tion on the features and capabilities of
SQL Server Profiler and how to use it, see Chapter 6, “SQL Server Profiler.”
SQL Profiler provides the following lock events that can be captured in a trace:
Lock:Acquired—Indicates when a lock on a resource, such as a data page or row,
has been acquired
Lock:Cancel—Indicates when the acquisition of a lock on a resource has been
canceled (for example, as the result of a deadlock)
Lock:Deadlock—Indicates when two or more concurrent processes have
dead-locked with each other
Lock:Deadlock Chain—Provides the information for each of the events leading up
to a deadlock This information is similar to that provided by the 1204 trace flag,
which is covered in the “Deadlocks” section, later in this chapter
Lock:Escalation—Indicates when a lower-level lock has been converted to a
higher-level lock (for example, when page-level locks are escalated to table-level
locks)
Lock:Released—Indicates that a process has released a previously acquired lock
on a resource
Lock:Timeout—Indicates that a lock request that is waiting on a resource has
timed out due to another transaction holding a blocking lock
Lock:Timeout (timeout >0)—Is similar to Lock:Timeoutbut does not include
any events where the lock timeout is 0 seconds
Deadlock Graph—Generates an XML description of a deadlock
Figure 37.1 shows an example of choosing a set of locking events to monitor with SQL
Server Profiler
Trang 3ptg SQL Server Profiler also provides a number of data values to display for the events being
monitored You might find the following data columns useful when monitoring locking
activity:
spid—The process ID of the process that generated the event
EventClass—The type of event being captured
Mode—For lock monitoring, the type of lock involved in the captured event
ObjectID—The ID of the object involved in the locking event—that is, the object
that the lock is associated with
DatabaseID—The ID of the database involved in the locking event
TextData—The query that generated the lock event
LoginName—The login name associated with the process
ApplicationName—The name of the application generating the lock event
Keep in mind that many internal system processes also acquire locks in SQL Server If you
want to filter out those processes and focus on specific processes, users, or applications,
you use the filters in SQL Server Profiler to include the information you want to trace or
exclude the information you don’t want to trace (see Figure 37.2)
After you set up your events, data columns, and filters, you can begin the trace Figure
37.3 shows an example of the type of information captured
FIGURE 37.1 Choosing lock events in SQL Server Profiler
Trang 41357 Monitoring Lock Activity in SQL Server
FIGURE 37.2 Filtering out unwanted information in SQL Server Profiler
Monitoring Locks with Performance Monitor
Another method of monitoring locking in SQL Server is through the Performance
Monitor The sys.dm_tran_locksview and SSMS Activity Monitor provide a snapshot of
the actual locks currently in effect in SQL Server If you want to monitor the locking
activity as a whole on a continuous basis, you can use the Windows Performance
Monitor and monitor the counters available for the SQLServer:Locksperformance
object (see Figure 37.4)
FIGURE 37.3 Lock information captured in a SQL Server Profiler trace
Trang 5FIGURE 37.4 Choosing counters for the SQLServer:Locks performance object in
Performance Monitor
NOTE
If you are monitoring a SQL Server 2008 named instance rather than a default
instance of SQL Server 2008, the SQL Server performance counters are listed under
the name of the SQL Server instance rather than under the generic SQLServer
perfor-mance counters
You can use the SQLServer:Locksobject to help detect locking bottlenecks and contention
points in the system as well as to provide a summary of the overall locking activity in SQL
Server You can use the information that Performance Monitor provides to identify
whether locking problems are the cause of any performance problems You can then take
appropriate corrective actions to improve concurrency and the overall performance of the
system The counters that belong to the SQLServer:Locksobject are as follows:
Average Wait Time—This counter represents the average wait time (in milliseconds)
for each lock request A high value is an indication of locking contention that could
be affecting performance of concurrent processes
Lock Requests/sec—This counter represents the total number of new locks and lock
conversion requests made per second A high value for this counter is not necessarily
a cause for alarm; it might simply indicate a system with a high number of
concur-rent users
Lock Timeouts (timeout > 0)/sec—This counter is similar to the LockTimeouts/sec
counter but does not include NOWAITlock requests that time out immediately
Trang 61359 SQL Server Lock Types
Lock Timeouts/sec—This counter represents the total number of lock timeouts per
second that occur for lock requests on a resource that cannot be granted before the
lock timeout interval is exceeded By default, a blocked process waits indefinitely
unless the application specifies a maximum timeout limit, using the SET
LOCK_TIMEOUTcommand A high value for this counter might indicate that the
timeout limit is set to a low value in the application or that you are experiencing
excessive locking contention
Lock Wait Time—This counter represents the cumulative wait time for each lock
request It is given in milliseconds A high value here indicates that you might have
long-running or inefficient transactions that are causing blocking and locking
contention
Lock Waits/sec—This counter represents the total number of lock requests
gener-ated per second for which a process had to wait before a lock request on a resource
was granted A high value might indicate inefficient or long-running transactions or
a poor database design that is causing a large number of transactions to block one
another
Number of Deadlocks/sec—This number represents the total number of lock
requests per second that resulted in deadlocks Deadlocks and ways to avoid them
are discussed in the “Deadlocks” section, later in this chapter
For more information on using Windows Performance Monitor for monitoring SQL Server
performance, see Chapter 39, “Monitoring SQL Server Performance.”
SQL Server Lock Types
Locking is handled automatically in SQL Server The Lock Manager chooses the type of
lock, based on the type of transaction (such as SELECT,INSERT,UPDATE, or DELETE) Lock
Manager uses the following types of locks:
Shared locks
Update locks
Exclusive locks
Intent locks
Schema locks
Bulk update locks
In addition to choosing the type of lock, the Lock Manager in SQL Server 2008
automati-cally adjusts the granularity of the locks (for example, row, page, table), based on the
nature of the statement that is executed and the number of rows that are affected
Trang 7Shared Locks
By default, SQL Server uses shared locks for all read operations A shared lock is, by
defini-tion, not exclusive Theoretically, an unlimited number of shared locks can be held on a
resource at any given time In addition, shared locks are unique in that, by default, a
process locks a resource only for the duration of the read on the resource (row, page, or
table) For example, the query SELECT * from authorslocks the first row in the authors
table when the query starts After the first row is read, the lock on that row is released,
and a lock on the second row is acquired After the second row is read, its lock is released,
and a lock on the third row is acquired, and so on In this fashion, a SELECTquery allows
other data rows that are not being read to be modified during the read operation This
increases concurrent access to the data
Shared locks are compatible with other shared locks as well as with update locks A shared
lock does not prevent the acquisition of additional shared locks or an update lock by
other processes on a given row or page Multiple shared locks can be held at any given
time, for a number of transactions or processes These transactions do not affect the
consistency of the data However, shared locks do prevent the acquisition of exclusive
locks Any transaction attempting to modify data on a page or a row on which a shared
lock is placed is blocked until all the shared locks are released
NOTE
It is important to note that within a transaction running at the default isolation level of
Read Committed, shared locks are not held for the duration of the transaction or even
the duration of the statement that acquires the shared locks Shared lock resources
(row, page, table, and so on) are normally released as soon as the read operation on
the resource is completed SQL Server provides the HOLDLOCKclause for the SELECT
statement, which you can use if you want to continue holding the shared lock for the
duration of the transaction HOLDLOCKis explained later in this chapter, in the section
“Table Hints for Locking.” Another way to hold shared locks for the duration of a
trans-action is to set the isolation level for the session or the query to Repeatable Read or
Serializable Reads
Update Locks
Update locks are used to lock rows or pages that a user process intends to modify When a
transaction tries to update a row, it must first read the row to ensure that it is modifying
the appropriate record If the transaction were to put a shared lock on the resource
initially, it would eventually need to get an exclusive lock on the resource to modify the
record and prevent any other transaction from modifying the same record The problem is
that this could lead to deadlocks in an environment in which multiple transactions are
trying to modify data on the same resource at the same time Figure 37.5 demonstrates
how deadlocks can occur if lock conversion takes place from shared locks to exclusive
locks When both processes attempt to escalate the shared lock they both hold on a
resource to an exclusive lock, it results in a deadlock situation
Trang 81361 SQL Server Lock Types
Update locks in SQL Server are provided to prevent this kind of deadlock scenario Update
locks are partially exclusive in that only one update lock can be acquired at a time on any
resource However, an update lock is compatible with shared locks, in that both can be
acquired on the same resource simultaneously In effect, an update lock signifies that a
process wants to change a record, and it keeps out other processes that also want to
change that record However, an update lock allows other processes to acquire shared
locks to read the data until theUPDATEorDELETEstatement is finished locating the records
to be affected The process then attempts to escalate each update lock to an exclusive
lock At this time, the process waits until all currently held shared locks on the same
records are released After the shared locks are released, the update lock is escalated to an
exclusive lock The data change is then carried out, and the exclusive lock is held for the
remainder of the transaction
NOTE
Update locks are not used just for update operations SQL Server uses update locks
any time a search for data is required prior to performing the actual modification, such
as with qualified updates and deletes (that is, when a WHEREclause is specified)
Update locks are also used for insertions into a table with a clustered index because
SQL Server must first search the data and clustered index to identify the correct
posi-tion at which to insert the new row to maintain the sort order After SQL Server has
found the correct location and begins inserting the record, it escalates the update lock
to an exclusive lock
Exclusive Locks
As mentioned earlier, an exclusive lock is granted to a transaction when it is ready to
perform data modifications An exclusive lock on a resource makes sure no other
transac-tion can interfere with the data locked by the transactransac-tion that is holding the exclusive
lock SQL Server releases the exclusive lock at the end of the transaction
Transaction 1
Update T1 SET coll=Coll
Acquires SHARED
lock
Needs an
EXCLUSIVE lock
Waits for Lock
Release by
Transaction 2
Transaction 2
Update T1 SET coll=Coll + 1
Acquires SHARED lock
Needs an EXCLUSIVE lock
Waits for Lock Release by Transaction 1 FIGURE 37.5 A deadlock scenario with shared and exclusive locks
Trang 9Exclusive locks are incompatible with other lock types If an exclusive lock is held on a
resource, any other read or data modification request for the same resource by other
processes is forced to wait until the exclusive lock is released Likewise, if a resource
currently has read locks held on it by other processes, the exclusive lock request is forced
to wait in a queue for the resource to become available
Intent Locks
Intent locks do not really constitute a locking mode; rather, they act as a mechanism to
indicate at a higher level of granularity the types of locks held at a lower level The types
of intent locks mirror the lock types previously discussed: shared intent locks, exclusive
intent locks, and update intent locks SQL Server Lock Manager uses intent locks as a
mechanism to indicate that a shared, update, or exclusive lock is held at a lower level For
example, a shared intent lock on a table by a process signifies that the process currently
holds a shared lock on a row or page within the table The presence of the intent lock
prevents other transactions from attempting to acquire a table-level lock that would be
incompatible with the existing row or page locks
Intent locks improve locking performance by allowing SQL Server to examine locks at the
table level to determine the types of locks held on the table at the row or page level rather
than searching through the multiple locks at the page or row level within the table Intent
locks also prevent two transactions that are both holding locks at a lower level on a
resource from attempting to escalate those locks to a higher level while the other
transac-tion still holds the intent lock This prevents deadlocks during lock escalatransac-tion
You typically see three types of intent locks when monitoring locking activity: intent
shared (IS) locks, intent exclusive (IX) locks, and shared with intent exclusive (SIX) locks
AnISlock indicates that the process currently holds, or has the intention of holding,
shared locks on lower-level resources (row or page) An IXlock indicates that the process
currently holds, or has the intention of holding, exclusive locks on lower-level resources
AnSIX(pronounced as the letters S-I-X, not like the number six) lock occurs under special
circumstances when a transaction is holding a shared lock on a resource, and later in the
transaction, an IXlock is needed At that point, the ISlock is converted to an SIXlock
In the following example, theSELECTstatement running at the serializable level acquires a
shared table lock It then needs an exclusive lock to update the row in thesales_bigtable:
SET TRANSACTION ISOLATION LEVEL serializable
go
BEGIN TRAN
select sum(qty) FROM sales_big
UPDATE sales_big
SET qty = 0
WHERE sales_id = 1001
COMMIT TRAN
Trang 101363 SQL Server Lock Types
Because the transaction initially acquired a shared (S) table lock and then needed an
exclusive row lock, which requires an intent exclusive (IX) lock on the table within the
same transaction, the Slock is converted to an SIXlock
NOTE
If only a few rows were insales_big, SQL Server might acquire only individual row or
key locks rather than a table-level lock SQL Server would then have an intent shared
(IS) lock on the table rather than a full shared (S) lock In that instance, theUPDATE
statement would then acquire a single exclusive lock to apply the update to a single
row, and theXlock at the key level would result in theISlocks at the page and table
levels being converted to anIXlock at the page and table level for the remainder of the
transaction
Schema Locks
SQL Server uses schema locks to maintain structural integrity of SQL Server tables Unlike
other types of locks that provide isolation for the data, schema locks provide isolation for
the schema of database objects, such as tables, views, and indexes within a transaction
The Lock Manager uses two types of schema locks:
Schema stability locks—When a transaction is referencing either an index or a
data page, SQL Server places a schema stability lock on the object This ensures that
no other process can modify the schema of an object—such as dropping an index or
dropping or altering a stored procedure or table—while other processes are still
refer-encing the object
Schema modification locks—When a process needs to modify the structure of an
object (for example, alter the table, recompile a stored procedure), the Lock Manager
places a schema modification lock on the object For the duration of this lock, no
other transaction can reference the object until the changes are complete and
com-mitted
Bulk Update Locks
A bulk update lock is a special type of lock used only when bulk copying data into a table
using the bcputility or the BULK INSERTcommand This special lock is used for these
operations only when either the TABLOCKhint is specified to bcpor the BULK INSERT
command or when the table lock on bulk loadtable option has been set for the table
Bulk update locks allow multiple bulk copy processes to bulk copy data into the same