网站中一些老页面仍采用Row_number类似的开窗函数进行分页处理,此时如果遭遇挖坟帖的情形可能就需要漫长的等待且消耗巨大.这里给大家介绍根据Row_number()特性采用特定锁Hint提升查询速度.
直接上菜
脚本环境可在SQL Server优化技巧之SQL Server中的"MapReduce"找到
如下查询在分页中比较常见
set statistics time on select * from (select ProductID, rn = ROW_NUMBER() OVER (ORDER BY ProductID)from [bigTransactionHistory]) as twhere t.rn between 15631801 and 15631802
这条查询在我的电脑上执行了15S,这还是数据全在内存中的情形!如图1-1
图1-1
一个简单的执行计划执行如此之长有点匪夷所思,毕竟逻辑读才6W多,且无物理读
,而且CPU时间与占用时间相差无几,排除了阻塞之类的因素后我们把消耗定位在这个查询本身上.这时提一个Row_number()的特点,它可在万千数据中将其序列化让我们找到我们想要的精确数据点,但就此默认的实现方式上是为每一行数据都加一个行锁.
我们开启Trace Flag 1200再次执行语句捕捉下执行时的锁.可以看到Row_number()在实现上未进行锁升级如图1-2
Code
dbcc traceon(3604,1200,-1)select * from (select ProductID, rn = ROW_NUMBER() OVER (ORDER BY ProductID)from [bigTransactionHistory]) as twhere t.rn between 15631801 and 15631802
View Code
Code
select * from (select ProductID, rn = ROW_NUMBER() OVER (ORDER BY ProductID)from [bigTransactionHistory] with(paglock)) as twhere t.rn between 15631801 and 15631802
View Code
图1-3
这里写了个简单的查询以便找到具体更新被锁住的行,如图2-1
Code
begin tran tttupdate dbo.[bigProduct] set size=111 where ProductID<1100-- rollback when finish test--rollback tran ttt--open another sessionSELECT * FROM [bigProduct] with(nolock)WHERE %%LOCKRES%% IN ( SELECT tl.resource_description FROM sys.dm_tran_locks AS tl INNER JOIN sys.partitions AS t2 ON t2.hobt_id = tl.resource_associated_entity_id WHERE t2.object_id = OBJECT_ID('bigProduct') AND tl.resource_type = 'KEY' )
图2-1
结语:系统内任何元素都有可能成为影响平衡的绊脚石.找到它,理解它,利用它.
认为有收获的同学请点赞.
原标题:SQL Server 利用锁提示优化Row_number()
关键词:sql