简体   繁体   English

SQL Server 数据库锁 - 使用 nolock 选择

[英]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?如果父视图使用 NOLOCK 从子视图中选择但子视图缺少NOLOCK,这会导致锁定吗?

IE: IE:

VIEW1:视图1:

    select * from view2 WITH (NOLOCK)

VIEW2:视图2:

    select * from hugetable

Would selecting from view1 effectively ignore the NOLOCK as this is missing in the definition of view2?从 view1 中选择是否会有效地忽略NOLOCK因为它在 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)连接 1(使用锁和未提交的行打开事务)

BEGIN TRAN

INSERT INTO dbo.Demo VALUES (4);

Connection 2连接 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.显示NOLOCK提示向下传播,它从未提交的事务中读取值4 (Selecting from dbo.[Inner] is blocked as expected) (从dbo.[Inner]选择按预期被阻止)

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

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