为什么要在删除临时表之前立即截断?
我看到一些代码,作者在删除临时表之前立即截断了临时表。这样做有理由吗?
TRUNCATE TABLE #Temp
DROP TABLE #Temp
I see some code where the author has truncated a temp table immediately before dropping the temp table. Is there a reason for doing this?
TRUNCATE TABLE #Temp
DROP TABLE #Temp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
另一个原因是 DROP TABLE 是一个完全记录的操作,因此通过首先截断(从不记录)可以降低事务日志记录开销。
Another reason is that a
DROP TABLE
is a fully logged operation, so by truncating first (which is never logged) you lower transactional logging overhead.可能作者的印象是,如果表已经为空,则 DROP TABLE 会更快,并且知道 TRUNCATE 会比 DELETE 更快。
Possibly the author was under the impression that DROP TABLE would be quicker if the table was already empty and knew that TRUNCATE would be quicker than DELETE.
在非常大的临时表上,有时先截断然后删除会更快,因为截断只是移动指针。通常不需要它,因为临时表会自行删除。
On very large temp tables, it's sometimes faster to truncate first then drop because truncate simply moves a pointer. It's normally not needed since temp tables drop on their own.
有可能是个傻瓜。 (并不是说我很完美)。
Could possibly be a knucklehead. (not that I'm perfect).
另一种可能性是,编码器试图避免临时表大于 8MB 时发生的延迟删除。即截断它然后丢弃它。我不确定 SQL 引擎是否会被这个愚弄,但它可能会强制同步清理。我不明白你为什么要这样做,也许是为了避免累积延迟掉落的一些问题(用于销毁的临时表)
Another possibility is that the coder is trying to avoid a delayed drop that will occur when temp table is larger than 8MB. I.e. truncate it then drop it. I'm not sure if the SQL engine will be fooled by this but it might force synchronous clean up. I can't see why you'd want to do this, maybe to avoid some problem with accumulating delayed drops (Temp tables for destruction)
可能是为了查看 TRUNCATE 命令是否因现有外键而引发异常?
Possibly to see if the
TRUNCATE
command throws an exception due to existing foreign keys?