简体   繁体   中英

SQL Server DB Locks - select with nolock

We have several views that call other views. If the parent view selects from the child view with NOLOCK but the child view is missing NOLOCKs could this cause a lock?

IE:

VIEW1:

    select * from view2 WITH (NOLOCK)

VIEW2:

    select * from hugetable

Would selecting from view1 effectively ignore the NOLOCK as this is missing in the definition of view2?

The documentation states

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view.

This is easy to test.

Setup

CREATE DATABASE Testing

GO

ALTER DATABASE Testing SET READ_COMMITTED_SNAPSHOT  OFF

GO

USE Testing 

GO

CREATE TABLE dbo.Demo(X int);

INSERT INTO dbo.Demo VALUES (1), (2), (3);

go

CREATE VIEW dbo.[Inner] AS 
SELECT *
FROM dbo.Demo

GO

CREATE VIEW dbo.[Outer] AS 
SELECT *
FROM dbo.[Inner]
WITH (NOLOCK)

Connection 1 (leaves a transaction open taking a lock and an uncommitted row)

BEGIN TRAN

INSERT INTO dbo.Demo VALUES (4);

Connection 2

SELECT *
FROM dbo.[Outer] 

Returns

X
-----------
1
2
3
4

Showing the NOLOCK hint was propagated down and it read value 4 from the uncommitted transaction. (Selecting from dbo.[Inner] is blocked as expected)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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