简体   繁体   English

SQL Server通过并发事务插入锁定

[英]SQL Server insert locking with concurrent transactions

Assume I have procedure A wrapped in a transaction that is using read uncommitted isolation level with an insert statement into table A that has an identity column followed by a series of select statements. 假设我将过程A封装在一个事务中,该事务使用读取未提交隔离级别,并在表A中插入一条语句,该语句具有一个标识列,后跟一系列选择语句。 The insert statement does not request a TABLOCKX. 插入语句不请求TABLOCKX。

If multiple calls are issued to this procedure in parallel will the calls be serialized because of the insert statement in the transaction or will they be allowed to execute concurrently? 如果并行向该过程发出多个调用,这些调用是否会由于事务中的插入语句而被序列化,或者将允许它们并行执行? I know if this was an update statement changing the exact same row for each call that they would be serialized but what about an insert statement with identity column? 我知道这是否是一条更新语句,它为将被序列化的每个调用更改了完全相同的行,但是带有标识列的插入语句又如何呢? Does this cause the transaction to hold an exclusive lock on the table for the duration of the transaction? 这会导致事务在事务期间对表持有排他锁吗?

Assume SQL server version is 2008 R2 if this makes a difference. 如果这有所不同,请假定SQL Server版本为2008 R2。

I don't have SQL 2008 handy, but in SQL 2012 it will allow any of the transactions to complete first (I assume it's the same in 2008). 我没有使用SQL 2008,但是在SQL 2012中,它将允许任何事务先完成(我认为在2008年是相同的)。

It's pretty easy to test, in SSMS. 在SSMS中测试非常容易。 First, create a table in your database: 首先,在数据库中创建一个表:

CREATE TABLE [dbo].[Test1](
    [ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [Value] [varchar](500) NULL,
) ON [PRIMARY]

Then in 2 different query windows run the following query: 然后在2个不同的查询窗口中运行以下查询:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin tran

    insert into test1 values (1)
    select * from test1

Note: the query is not rolled back or committed. 注意:查询不会回滚或提交。

If you run the queries without the 1st line then the 1st query will run and wait then the 2nd will be sequential. 如果您在没有第一行的情况下运行查询,则第一条查询将运行并等待,然后第二条将是顺序的。 If you run with transaction isolation level set to Read Uncommitted then the 2nd query will finish. 如果在事务隔离级别设置为“ Read Uncommitted运行,则第二个查询将完成。 You can commit or rollback the 1st query and the results of the 2nd will be unaffected. 您可以提交或回滚第一个查询,而第二个查询的结果将不受影响。

use WITH (NOLOCK) with select query. 与选择查询一起使用WITH(NOLOCK) it's give output evenif that table or row is in updation. 即使表或行正在更新,它也会提供输出。 it's give output last committed data. 给输出最后提交的数据。

for ex. 对于前。

select * form tablename with(nolock)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM