Reputation: 541
Below is the sample query, consider 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?
So when actual data is written on the page table is locked but not during select even though it is INSERT INTO with SELECT?
Upvotes: 3
Views: 15953
Reputation: 1
Those two steps are the logical steps for query execution. What SQL Server can do/do at physical level is another story. 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. 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.
If you want to take an X lock on target table then you could use
INSERT INTO Target WITH(TABLOCKX) (Col1,Col2,Col3,Col4)
SELECT ...
If you want minimally logged inserts then please read this article.
Upvotes: 2
Reputation: 117
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
Upvotes: 0