简体   繁体   English

通过临时表更新

[英]Update via a temp table

So I have a rather large table (150 million rows) that data scrub queries get run on nightly. 因此,我有一个很大的表(1.5亿行),数据清理查询每天晚上运行。 Now these queries don't update a lot of records, but to get the records needed, that have to query that single table multiple times in sub queries, which takes some time. 现在,这些查询不会更新很多记录,而是要获取所需的记录,这些记录必须在子查询中多次查询单个表,这需要一些时间。

So, would it be better for me to do a normal update statement, or would it be better if I put the few results I needed in a temp table, and then just did an update for those few rows, which would greatly reduce the locks during update. 因此,对我来说,执行常规的update语句会更好,还是将一些所需的结果放入临时表中,然后对这几行进行更新会更好,这将大大减少锁在更新期间。

I'm unsure how an update statement locks work when most of the time is spent querying. 我不确定大部分时间用于查询时,更新语句如何锁定。 If it is going to only update 5 records, and runs for half and hour, will it release a record that it updated in the first minute, or does it wait till the end of the query? 如果只更新5条记录,并且运行了半小时,它将发布在第一分钟更新的记录,还是等到查询结束?

Thanks 谢谢

You need to use (and look into) into the ROWLOCK table hint. 您需要使用(并研究) ROWLOCK表提示。 You can use it with the update statement while updating in batches of 5000 rows of less. 您可以将其与update语句一起使用,同时以少于5000行的批量进行更新。 This will attempt to place row locks in the target table (or on index keys, if a covering index is present). 这将尝试在目标表中(或如果存在覆盖索引,则在索引键上)放置行锁。 If for some reason that fails, the lock will be escalated to a table lock. 如果由于某种原因失败,则该锁将升级为表锁。

From MSDN (as for reasons why lock escalation might occur): 从MSDN (作为可能导致锁升级的原因):

When the Database Engine checks for possible escalations at every 1250 newly acquired locks, a lock escalation will occur if and only if a Transact-SQL statement has acquired at least 5000 locks on a single reference of a table. 当数据库引擎检查每1250个新获取的锁是否有可能升级时,只有且仅当Transact-SQL语句已在表的单个引用上获取了至少5000个锁时,才会发生锁升级。 Lock escalation is triggered when a Transact-SQL statement acquires at least 5,000 locks on a single reference of a table. 当Transact-SQL语句在表的单个引用上获取至少5,000个锁时,将触发锁升级。 For example, lock escalation is not triggered if a statement acquires 3,000 locks in one index and 3,000 locks in another index of the same table. 例如,如果一条语句在同一表的一个索引中获得3,000个锁,而在另一个表中获得3,000个锁,则不会触发锁升级。 Similarly, lock escalation is not triggered if a statement has a self join on a table, and each reference to the table only acquires 3,000 locks in the table. 同样,如果语句在表上具有自联接,则不会触发锁升级,并且对表的每个引用仅在表中获取3,000个锁。

Actually, there's more to read in this last article. 实际上,在上一篇文章中还有更多要阅读的内容。 You should have a look at mixed lock type escalation section. 您应该查看混合锁类型升级部分。

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

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