Sql who is locking table




















Used to protect key ranges in serializable transactions. Page 8 kilobyte — KB data page or index page. Extent Contiguous group of eight data pages or index pages. Table Entire table, including all data and indexes. DB Database. SQL Server locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions. Update U Used on resources that can be updated. Prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.

Ensures that multiple updates cannot be made to the same resource at the same time. Intent Used to establish a lock hierarchy. Schema Used when an operation dependent on the schema of a table is executing.

The types of schema locks are: schema modification Sch-M and schema stability Sch-S. No other transactions can modify the data while shared S locks exist on the resource. The rollback itself may block users or cause a long database recovery time if you restart the SQL Server service. You must restart the SQL Server service for a new startup parameter to take effect. Turning on the trace flag prevents any future lock escalations, but it does not reverse any lock escalations that have already occurred in an active transaction.

Lock hints do not prevent lock escalation. Memory threshold is reached - A memory threshold of 40 percent of lock memory is reached. When lock memory exceeds 24 percent of the buffer pool, a lock escalation can be triggered. Lock memory is limited to 60 percent of the visible buffer pool. The lock escalation threshold is set at 40 percent of the lock memory.

This is 40 percent of 60 percent of the buffer pool, or 24 percent. If lock memory exceeds the 60 percent limit this is much more likely if lock escalation is disabled , all attempts to allocate additional locks fail, and errors are generated. A lock threshold is reached - After memory threshold is checked, the number of locks acquired on the current table or index is assessed.

If the number exceeds 5,, a lock escalation is triggered. Also, examine the IntegerData and IntegerData2 columns. The methods that are discussed in the Prevent Lock Escalation section are better options than disabling escalation at the table or instance level.

Additionally, the preventive methods generally produce better performance for the query than disabling lock escalation. Microsoft recommends that you enable this trace flag only to mitigate severe blocking that is caused by lock escalation while other options, such as those discussed in this article, are being investigated. Feedback will be sent to Microsoft: By pressing the submit button, your feedback will be used to improve Microsoft products and services.

Returns a virtual table that displays all version records in the common version store. Returns a virtual table that displays the total space in tempdb used by version store records for each database. Returns a virtual table for all active transactions in all databases within the SQL Server instance that use row versioning.

System transactions do not appear in this DMV. Returns a virtual table that displays snapshots taken by each transaction. The snapshot contains the sequence number of the active transactions that use row versioning. Returns a single row that displays row versioning-related state information of the transaction in the current session.

Returns a virtual table that displays all active transactions at the time the current snapshot isolation transaction starts.

If the current transaction is using snapshot isolation, this function returns no rows. The following performance counters monitor tempdb and the version store, as well as transactions using row versioning.

Free Space in tempdb KB. Monitors the amount, in kilobytes KB , of free space in the tempdb database. There must be enough free space in tempdb to handle the version store that supports snapshot isolation. The following formula provides a rough estimate of the size of the version store. For long-running transactions, it may be useful to monitor the generation and cleanup rate to estimate the maximum size of the version store. The longest running time of transactions should not include online index builds.

Because these operations may take a long time on very large tables, online index builds use a separate version store. The approximate size of the online index build version store equals the amount of data modified in the table, including all indexes, while the online index build is active.

Version Store Size KB. Monitors the size in KB of all version stores. This information helps determine the amount of space needed in the tempdb database for the version store. Monitoring this counter over a period of time provides a useful estimate of additional space needed for tempdb.

Monitors the version generation rate in KB per second in all version stores. Monitors the version cleanup rate in KB per second in all version stores. Version Store unit creation. Monitors the total number of version store units created to store row versions since the instance was started. Version Store unit truncation. Monitors the total number of version store units truncated since the instance was started.

A version store unit is truncated when SQL Server determines that none of the version rows stored in the version store unit are needed to run active transactions. Update conflict ratio. Monitors the ratio of update snapshot transaction that have update conflicts to the total number of update snapshot transactions. Longest Transaction Running Time.

Monitors the longest running time in seconds of any transaction using row versioning. This can be used to determine if any transaction is running for an unreasonable amount of time. Monitors the total number of active transactions.

This does not include system transactions. Update Snapshot Transactions. Monitors the total number of active snapshot transactions that perform update operations. NonSnapshot Version Transactions. Monitors the total number of active non-snapshot transactions that generate version records. The sum of Update Snapshot Transactions and NonSnapshot Version Transactions represents the total number of transactions that participate in version generation.

The difference of Snapshot Transactions and Update Snapshot Transactions reports the number of read-only snapshot transactions. The following examples show the differences in behavior between snapshot isolation transactions and read-committed transactions that use row versioning.

In this example, a transaction running under snapshot isolation reads data that is then modified by another transaction. The snapshot transaction does not block the update operation executed by the other transaction, and it continues to read data from the versioned row, ignoring the data modification. However, when the snapshot transaction attempts to modify the data that has already been modified by the other transaction, the snapshot transaction generates an error and is terminated.

In this example, a read-committed transaction using row versioning runs concurrently with another transaction. The read-committed transaction behaves differently than a snapshot transaction. Like a snapshot transaction, the read-committed transaction will read versioned rows even after the other transaction has modified data.

However, unlike a snapshot transaction, the read-committed transaction will:. The database does not have to be in single-user mode.

After all of the modification transactions complete, the state of the option is changed to ON. Users cannot start a snapshot transaction in that database until the option is fully ON. Use the sys. All updates to user tables and some system tables stored in master and msdb generate row versions. The row versioning framework is always enabled in SQL Server, and is used by multiple features.

Besides providing row versioning-based isolation levels, it is used to support modifications made in triggers and multiple active result sets MARS sessions, and to support data reads for ONLINE index operations. Row versioning-based isolation levels are enabled at the database level. Any application accessing objects from enabled databases can run queries using the following isolation levels:. A transaction running under snapshot isolation can access tables in the database that have been enabled for snapshot.

To access tables that have not been enabled for snapshot, the isolation level must be changed. For example, the following code example shows a SELECT statement that joins two tables while running under a snapshot transaction.

One table belongs to a database in which snapshot isolation is not enabled. The following code example shows the same SELECT statement that has been modified to change the transaction isolation level to read-committed. Global temp tables are stored in tempdb. When accessing global temp tables inside a snapshot transaction, one of the following must happen:. Distributed transactions, including queries in distributed partitioned databases, are not supported under snapshot isolation.

SQL Server does not keep multiple versions of system metadata. Data definition language DDL statements on tables and other database objects indexes, views, data types, stored procedures, and common language runtime functions change metadata. If a DDL statement modifies an object, any concurrent reference to the object under snapshot isolation causes the snapshot transaction to fail.

Read-committed transactions using row versioning are not affected. When this happens, concurrent snapshot isolation transactions accessing bulk inserted tables fail. When an instance of the Microsoft SQL Server Database Engine cannot grant a lock to a transaction because another transaction already owns a conflicting lock on the resource, the first transaction becomes blocked waiting for the existing lock to be released.

By default, there is no mandatory time-out period and no way to test whether a resource is locked before locking it, except to attempt to access the data and potentially get blocked indefinitely.

In SQL Server, use the sys. Any transaction containing the statement, however, is not rolled back or canceled by SQL Server. Therefore, the application must have an error handler that can trap error message If an application does not trap the error, the application can proceed unaware that an individual statement within a transaction has been canceled, and errors can occur because statements later in the transaction might depend on the statement that was never executed.

Implementing an error handler that traps error message allows an application to handle the time-out situation and take remedial action, such as: automatically resubmitting the statement that was blocked or rolling back the entire transaction.

If an application must operate at a different isolation level, it can use the following methods to set the isolation level:. When the isolation level is specified, the locking behavior for all queries and data manipulation language DML statements in the SQL Server session operates at that isolation level.

The isolation level remains in effect until the session terminates or until the isolation level is set to another level. The isolation level can be overridden for individual query or DML statements, if necessary, by specifying a table-level hint. Specifying a table-level hint does not affect other statements in the session. We recommend that table-level hints be used to change the default behavior only when absolutely necessary.

The SQL Server Database Engine might have to acquire locks when reading metadata even when the isolation level is set to a level where share locks are not requested when reading data. For example, a transaction running at the read-uncommitted isolation level does not acquire share locks when reading data, but might sometime request locks when reading a system catalog view. This means it is possible for a read uncommitted transaction to cause blocking when querying a table when a concurrent transaction is modifying the metadata of that table.

The result set may vary from the result set on your system. The hints specify the type of locking or row versioning the instance of the SQL Server Database Engine uses for the table data. Table-level locking hints can be used when a finer control of the types of locks acquired on an object is required.

These locking hints override the current transaction isolation level for the session. We recommend that table-level locking hints be used to change the default locking behavior only when necessary. Disallowing a locking level can adversely affect concurrency. The SQL Server Database Engine might have to acquire locks when reading metadata, even when processing a select with a locking hint that prevents requests for share locks when reading data.

The only lock taken that references HumanResources. Employee is a schema stability Sch-S lock. In this case, serializability is no longer guaranteed. In SQL Server This option is not a locking hint, but can be used to reduce lock escalation. The SQL Server Database Engine uses a dynamic locking strategy that automatically chooses the best locking granularity for queries in most cases.

We recommend that you do not override the default locking levels, which have page and row locking on, unless table or index access patterns are well understood and consistent, and there is a resource contention problem to solve. Overriding a locking level can significantly impede concurrent access to a table or index. For example, specifying only table-level locks on a large table that users access heavily can cause bottlenecks because users must wait for the table-level lock to be released before accessing the table.

There are a few cases where disallowing page or row locking can be beneficial, if the access patterns are well understood and consistent.

For example, a database application uses a lookup table that is updated weekly in a batch process. Concurrent readers access the table with a shared S lock and the weekly batch update accesses the table with an exclusive X lock.

Turning off page and row locking on the table reduces the locking overhead throughout the week by allowing readers to concurrently access the table through shared table locks. When the batch job runs, it can complete the update efficiently because it obtains an exclusive table lock. Turning off page and row locking might or might not be acceptable because the weekly batch update will block the concurrent readers from accessing the table while the update runs.

If the batch job only changes a few rows or pages, you can change the locking level to allow row or page level locking, which will enable other sessions to read from the table without blocking. If the batch job has a large number of updates, obtaining an exclusive lock on the table may be the best way to ensure the batch job finishes efficiently.

Occasionally a deadlock occurs when two concurrent operations acquire row locks on the same table and then block because they both need to lock the page. Disallowing row locks forces one of the operations to wait, avoiding the deadlock.

The lock settings apply to both the index pages and the table pages. Page-level locks, row-level locks, or a combination of page-level and row-level locks can be disallowed for a given index. Explicit transactions can be nested. This is primarily intended to support transactions in stored procedures that can be called either from a process already in a transaction or from processes that have no active transaction. The following example shows the intended use of nested transactions.

The procedure TransProc enforces its transaction regardless of the transaction mode of any process that executes it. If TransProc is called when a transaction is active, the nested transaction in TransProc is largely ignored, and its INSERT statements are committed or rolled back based on the final action taken for the outer transaction. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed.

If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether or not the inner transactions were individually committed. Bound sessions ease the coordination of actions across multiple sessions on the same server.

Bound sessions allow two or more sessions to share the same transaction and locks, and can work on the same data without lock conflicts. Bound sessions can be created from multiple sessions within the same application or from multiple applications with separate sessions. A bind token is a character string that uniquely identifies each bound transaction.

The bind token is then sent to the other sessions to be bound with the current session. Bind tokens must be transmitted from the application code that makes the first session to the application code that subsequently binds their sessions to the first session. There is no Transact-SQL statement or API function that an application can use to get the bind token for a transaction started by another process.

Some of the methods that can be used to transmit a bind token include the following:. If the sessions are all initiated from the same application process, bind tokens can be stored in global memory or passed into functions as a parameter. If the sessions are made from separate application processes, bind tokens can be transmitted using interprocess communication IPC , such as a remote procedure call RPC or dynamic data exchange DDE.

Bind tokens can be stored in a table in an instance of the SQL Server Database Engine that can be read by processes wanting to bind to the first session. Only one session in a set of bound sessions can be active at any time.

If one session is executing a statement on the instance or has results pending from the instance, no other session bound to it can access the instance until the current session finishes processing or cancels the current statement. If the instance is busy processing a statement from another of the bound sessions, an error occurs indicating that the transaction space is in use and the session should retry later. When you bind sessions, each session retains its isolation level setting.

Local bound session Allows bound sessions to share the transaction space of a single transaction in a single instance of the SQL Server Database Engine.

Distributed bound session Allows bound sessions to share the same transaction across two or more instances until the entire transaction is either committed or rolled back by using Microsoft Distributed Transaction Coordinator MS DTC. Distributed bound sessions are not identified by a character string bind token; they are identified by distributed transaction identification numbers. In earlier versions of SQL Server, bound sessions were primarily used in developing extended stored procedures that must execute Transact-SQL statements on behalf of the process that calls them.

Having the calling process pass in a bind token as one parameter of the extended stored procedure allows the procedure to join the transaction space of the calling process, thereby integrating the extended stored procedure with the calling process. Bound sessions can be used to develop three-tier applications in which business logic is incorporated into separate programs that work cooperatively on a single business transaction.

These programs must be coded to carefully coordinate their access to a database. Because the two sessions share the same locks, the two programs must not try to modify the same data at the same time. At any point in time, only one session can be doing work as part of the transaction; there can be no parallel execution. The transaction can only be switched between sessions at well-defined yield points, such as when all DML statements have completed and their results have been retrieved.

It is important to keep transactions as short as possible. When a transaction is started, a database management system DBMS must hold many resources until the end of the transaction to protect the atomicity, consistency, isolation, and durability ACID properties of the transaction. If data is modified, the modified rows must be protected with exclusive locks that prevent any other transaction from reading the rows, and exclusive locks must be held until the transaction is committed or rolled back.

Depending on transaction isolation level settings, SELECT statements may acquire locks that must be held until the transaction is committed or rolled back. Especially in systems with many users, transactions must be kept as short as possible to reduce locking contention for resources between concurrent connections.

Long-running, inefficient transactions may not be a problem with small numbers of users, but they are intolerable in a system with thousands of users. Delayed durable transactions do not guarantee durability. See the topic Transaction Durability for more information. Do not require input from users during a transaction. Get all required input from users before a transaction is started. If additional user input is required during a transaction, roll back the current transaction and restart the transaction after the user input is supplied.

Even if users respond immediately, human reaction times are vastly slower than computer speeds. All resources held by the transaction are held for an extremely long time, which has the potential to cause blocking problems. If users do not respond, the transaction remains active, locking critical resources until they respond, which may not happen for several minutes or even hours.

Do not open a transaction while browsing through data, if at all possible. Transactions should not be started until all preliminary data analysis has been completed. Keep the transaction as short as possible. After you know the modifications that have to be made, start a transaction, execute the modification statements, and then immediately commit or roll back. Do not open the transaction before it is required.

Make intelligent use of lower transaction isolation levels. Many applications can be readily coded to use a read-committed transaction isolation level. Not all transactions require the serializable transaction isolation level. Make intelligent use of lower cursor concurrency options, such as optimistic concurrency options. In a system with a low probability of concurrent updates, the overhead of dealing with an occasional "somebody else changed your data after you read it" error can be much lower than the overhead of always locking rows as they are read.

Access the least amount of data possible while in a transaction. This lessens the number of locked rows, thereby reducing contention between transactions.

Avoid pessimistic locking hints such as holdlock whenever possible. Avoid using Implicit transactions when possible Implicit transactions can introduce unpredictable behavior due to their nature. See Implicit Transactions and concurrency problems.

Design indexes with a reduced fill factor Decreasing the fill factor may help you prevent or decrease fragmentation of index pages and thus reduce index seek times especially when retrieved from disk. To view fragmentation information for the data and indexes of a table or view, you can usesys. To prevent concurrency and resource problems, manage implicit transactions carefully.

This can cause a new transaction to be opened while the application browses through data, or even when it requires input from the user. After completing the last transaction required to protect data modifications, turn off implicit transactions until a transaction is once again required to protect data modifications. This process lets the SQL Server Database Engine use autocommit mode while the application is browsing data and getting input from the user.

In addition, when the snapshot isolation level is enabled, although a new transaction will not hold locks, a long-running transaction will prevent the old versions from being removed from tempdb. A long-running transaction is an active transaction that has not been committed or roll backed the transaction in a timely manner. For example, if the beginning and end of a transaction is controlled by the user, a typical cause of a long-running transaction is a user starting a transaction and then leaving while the transaction waits for a response from the user.

If a server instance is shut down after an active transaction has performed many uncommitted modifications, the recovery phase of the subsequent restart can take much longer than the time specified by the recovery interval server configuration option or by the ALTER DATABASE These options control the frequency of active and indirect checkpoints, respectively.

More importantly, although a waiting transaction might generate very little log, it holds up log truncation indefinitely, causing the transaction log to grow and possibly fill up. If the transaction log fills up, the database cannot perform any more updates. This dynamic management view returns information about transactions at the database level.

This statement lets you identify the user ID of the owner of the transaction, so you can potentially track down the source of the transaction for a more orderly termination committing it rather than rolling it back. You may have to use the KILL statement. Use this statement very carefully, however, especially when critical processes are running. Overhead of Row Versioning Extended Events sys.

Feedback will be sent to Microsoft: By pressing the submit button, your feedback will be used to improve Microsoft products and services.

Privacy policy. Skip to main content. This browser is no longer supported. Download Microsoft Edge More info. Contents Exit focus mode. Note Under connections enabled to support multiple active result sets MARS , an explicit transaction started through an API function cannot be committed while there are pending requests for execution.

Important Choosing a transaction isolation level does not affect the locks acquired to protect data modifications. Note An intent exclusive IX lock is compatible with an IX lock mode because IX means the intention is to update only some of the rows rather than all of them. Note The internal Null lock mode is compatible with all other lock modes. I have a SQL table that all of a sudden cannot return data unless I include with nolock on the end, which indicates some kind of lock left on my table.

I've experimented a bit with sys. Different versions of SSMS put the activity monitor in different places. For example, SSMS and have it in the context menu when you right-click on a server node. For what the lock level abbreviations mean, see e. NB the [Xclusive lock for command] column can be misleading -- it shows the current command for that spid; but the X lock could have been triggered by an earlier command in the transaction.

Having spids, you could check activity monitor processes tab to find out what processes are locking the tables "details" for more info and "kill process" to kill it.

I have a stored procedure that I have put together, that deals not only with locks and blocking, but also to see what is running in a server.

I have put it in master. I will share it with you, the code is below:. Jonathan Kehayias. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. This dynamic management object returns information about currently active lock manager resources. Each row represents a currently active request to the lock manager for a lock that has been granted or is waiting to be granted.

You can very easily find what is blocking your queries and tons of other handy information. Each query is executing in separate query window:. The routine has a lot of parameters, so you can check the docs for more details. If we query the sys. You can have orphaned distributed transactions holding exclusive locks and you will not see them if your script assumes there is a session associated with the transaction there isn't!

Run the script below to identify these transactions:.



0コメント

  • 1000 / 1000