Before always thought Insert no lock on the table, but it is not the case, here are some examples and proof.
CREATE TABLE [dbo].[TEST1]( [C1] [varchar](100) NULL, [C2] [varchar](100) NULL, [C3] [varchar](100) NULL ) set nocount on declare @a int=1 begin tran while @a <= 100000 begin insert into test1 select change (), change (), change () sets @a = @a + 1 end
1 execute the following instructions in the session window:
BEGIN TRAN insert into TEST1 select ' 1 ' , ' 2 ' , ' 3 '
2 execute the following instructions in the session window:
SELECT * FROM TEST1 where C1 ='D638C'
You will find the instruction session 2 has been waiting to see concrete lock case
SELECT request_owner_id , resource_type, request_mode, resource_description, request_session_id, request_status, resource_associated_entity_id, DB_NAME(resource_database_id)as resource_database FROM sys.dm_tran_locks WHERE resource_type <> 'DATABASE' AND DB_NAME(resource_database_id)='CustomDB' ORDER BY request_owner_id;
Note: request_owner_id: you open two windows, request_owner_id there are two
As shown above, 1: indicates that the insert statements in a row above plus, 2: query submitted in the waiting session 1 Conclusions: In the table there is no primary key, insert statements will lead to lock the entire table, the entire table can not be queried.
The following discussions of the primary key:
CREATE TABLE [dbo].[TEST2]( [C1] [varchar](100)not NULL, [C2] [varchar](100) NULL, [C3] [varchar](100) NULL ) set nocount on declare @a int=1 begin tran While @a <= 100000 begin insert into [ TEST2 ] select @a , change (), change () sets @a = @a + 1 end alter table [ TEST2 ] add constraint TTT primary cyfnod (C1)
Session 1:
BEGIN TRAN insert into [TEST2] select '00101','2','3' -- COMMIT TRAN
Session 2:
SELECT * FROM TEST2 where C1 ='00101'
Session 3:
SELECT * FROM TEST2 where C1 ='1'
Session 4:
SELECT * FROM TEST2 where C2 ='6900B68A-F4ED-4B44-875A-365C80F8D28A'
You will find the session 2,4 blocked, but the session 3 is capable of performing, the conclusion: the table has a primary key, and when you use the primary key query , insert only lock primary key value.