简体   繁体   English

批量插入期间的SQL Server表锁定

[英]SQL Server Table Lock during bulk insert

Below is the sample query, consider A 下面是示例查询,请考虑A.

INSERT INTO Target (Col1,Col2,Col3,Col4) ----------------Statement#1
Select A.Col1,B.Col2,A.Col3,C.Col4       ----------------Statement#2
FROM A WITH(NOLOCK) INNER JOIN B WITH(NOLOCK)
    ON A.Id = B.ID
    LEFT JOIN C WITH NOLOCK
    ON C.Id = B.ID
Where A.Id = 11

At which stage the lock will be applied on table [exclusive lock?], how SQL is going to execute the query? 在哪个阶段,锁将应用于表[exclusive lock?],SQL将如何执行查询?

  1. Result will be fetched from table A, B and C based on join and where clause. 将根据join和where子句从表A,B和C中获取结果。
  2. On ready result, start inserting data in table and at same time apply the lock on table. 准备好结果时,开始在表中插入数据,同时在表上应用锁定。

So when actual data is written on the page table is locked but not during select even though it is INSERT INTO with SELECT? 因此,当页面上的实际数据被锁定但是在选择期间不会被锁定,即使它是SELECT INSERT INTO吗?

Those two steps are the logical steps for query execution. 这两个步骤是查询执行的逻辑步骤。 What SQL Server can do/do at physical level is another story. SQL Server在物理层面上可以做什么/做什么是另一回事。 At this moment: 此刻:

INSERT INTO Target (Col1,Col2,Col3,Col4) ----------------Statement#1
Select A.Col1,B.Col2,A.Col3,C.Col4       ----------------Statement#2
FROM A WITH(NOLOCK) INNER JOIN B WITH(NOLOCK)
    ON A.Id = B.ID
    LEFT JOIN C WITH NOLOCK
    ON C.Id = B.ID
Where A.Id = 11

for every output record (see SELECT clause) it takes an X lock on a RID or a KEY within target table ( RID for heap / KEY for clustered index) and it inserts that record. 对于每个输出记录(请参阅SELECT子句),它对目标表中的RIDKEY进行X lock (对于聚簇索引的堆/ KEY RID )并插入该记录。 This steps are repeated for every output record. 对每个输出记录重复此步骤。 So, it doesn't read all records from source tables and only after this step it starts inserting records into target table. 因此,它不会从源表中读取所有记录,只有在此步骤之后才开始将记录插入目标表中。 Because of NOLOCK table hint on source table it will takes only Sch-S (schema stability) locks on these tables. 由于源表上的NOLOCK表提示,这些表上只需要Sch-S(模式稳定性)锁。

If you want to take an X lock on target table then you could use 如果你想在目标表上进行X锁定,那么你可以使用

INSERT INTO Target WITH(TABLOCKX) (Col1,Col2,Col3,Col4)
SELECT ...

If you want minimally logged inserts then please read this article . 如果您想要最少记录的插入,请阅读本文

Did you specify any "Table Lock" hint. 您是否指定了任何“表格锁定”提示。 If you want to Row-level lock Set "Table Lock" to off. 如果要将行级锁定设置为“表锁定”关闭。

or check this it will help you... 或检查它会帮助你...

http://technet.microsoft.com/en-us/library/ms180876(v=sql.105).aspx http://technet.microsoft.com/en-us/library/ms180876(v=sql.105).aspx

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

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