SQL Server 2008中的临时表上的sql-server – nolock

前端之家收集整理的这篇文章主要介绍了SQL Server 2008中的临时表上的sql-server – nolock前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
添加(Nolock)会从临时表中选择时减少争用,还是sql Server足够聪明,不能首先创建对临时表的争用?

PS:是的,我知道READUNCOMMITTED的危险.

select * from #myTempTable

VS

select * from #myTempTable with (nolock) --is this faster?

解决方法

您可以使用跟踪标志1200(在我认为这是全局的开发机器上)来查看为自己取出的锁
SET NOCOUNT ON;

CREATE TABLE ##T
(
X INT
)

INSERT INTO ##T 
SELECT number
FROM master..spt_values

CREATE TABLE #T
(
X INT
)
INSERT INTO #T
SELECT *
FROM ##T

/*Run the commands first with the trace flag off so the locking
info is less full of irrelevant stuff about plan compilation 
*/
GO

PRINT '##T Read Committed'
SELECT COUNT(*) FROM ##T
PRINT '##T NOLOCK'
SELECT COUNT(*) FROM ##T WITH (NOLOCK)
PRINT '##T Finished'

GO

PRINT '#T Read Committed'
SELECT COUNT(*) FROM #T
PRINT '#T NOLOCK'
SELECT COUNT(*) FROM #T WITH (NOLOCK)
PRINT '#T Finished'

GO

DBCC TRACEON(-1,3604)
DBCC TRACEON(-1,1200)

GO

PRINT '##T Read Committed'
SELECT COUNT(*) FROM ##T
PRINT '##T NOLOCK'
SELECT COUNT(*) FROM ##T WITH (NOLOCK)
PRINT '##T Finished'

GO

PRINT '#T Read Committed'
SELECT COUNT(*) FROM #T
PRINT '#T NOLOCK'
SELECT COUNT(*) FROM #T WITH (NOLOCK)
PRINT '#T Finished'

GO

DBCC TRACEOFF(-1,3604)
DBCC TRACEOFF(-1,1200)

DROP TABLE ##T
DROP TABLE #T

对于一个全球的临时表,这并不奇怪,使得更多的区别.

尽管如此,本地#temp表的锁类型仍然存在较小差异.我再现下面输出的那部分输出

#T Read Committed
Process 56 acquiring IS lock on OBJECT: 2:301244128:0  (class bit0 ref1) result: OK

Process 56 acquiring S lock on OBJECT: 2:301244128:0  (class bit0 ref1) result: OK

Process 56 releasing lock on OBJECT: 2:301244128:0 

#T NOLOCK
Process 56 acquiring Sch-S lock on OBJECT: 2:301244128:0  (class bit0 ref1) result: OK

Process 56 acquiring S lock on HOBT: 2:9079256880114171904 [BULK_OPERATION] (class bit0 ref1) result: OK

Process 56 releasing lock on OBJECT: 2:301244128:0

编辑:上面的结果是一个堆.对于具有聚簇索引的临时表,结果如下.

#T Read Committed
Process 55 acquiring IS lock on OBJECT: 2:1790629422:0  (class bit0 ref1) result: OK

Process 55 acquiring S lock on OBJECT: 2:1790629422:0  (class bit0 ref1) result: OK

Process 55 releasing lock on OBJECT: 2:1790629422:0 

#T NOLOCK
Process 55 acquiring Sch-S lock on OBJECT: 2:1790629422:0  (class bit0 ref1) result: OK

Process 55 releasing lock on OBJECT: 2:1790629422:0 

#T Finished

堆版本上的BULK_OPERATION锁的原因是explained here.但是可以看出,锁定开销是非常小的.

原文链接:https://www.f2er.com/mssql/76230.html

猜你在找的MsSQL相关文章