优化问题:将触发器 INSERTED 或 DELETED 行复制到表变量中
我一直遇到 SQL 触发器的性能问题。该问题与在 INSERTED 触发器表中使用 select 语句时执行 SQL 查询有关。
SELECT x FROM y WHERE x IN ( SELECT x FROM INSERTED )
查询执行计划指向 ( SELECT x FROM INSERTED )
花费的时间比预期长得多。我们在这里讨论的是 x1000 行。
如果我创建一个表变量,然后从 INSERTED 中选择行到表变量中,然后在“IN”子句中使用表变量,速度会快得多。
我的问题是为什么这样更快?我已经知道它可能是什么了。我读到 INSERTED 表是一个虚拟表,它来自事务日志,因此读取时间比使用表变量要长得多。但是,我认为从 INSERTED 表中选择行到表变量中会抵消在“IN”子句中使用表变量的积极效果。
有什么想法为什么这更快吗?
I've been having performance problems with an SQL trigger. The problem relates to performing an SQL query when using a select statement with the INSERTED trigger table.
SELECT x FROM y WHERE x IN ( SELECT x FROM INSERTED )
The query execution plan points to the ( SELECT x FROM INSERTED )
taking much longer than expected. We are talking x1000s of rows here.
If I create a table variable, and I select the rows from INSERTED into the table variable, then use the table variable within the 'IN' clause it is MUCH faster.
My question is why is this faster? I've already got an idea what it might be. I've read that the INSERTED table is a virtual table and this comes from the transaction logs and so takes substantially longer to read than using the table variable. However, I would have thought selecting the rows from the INSERTED table into the table variable would negate the positive effects of using the table variable within the 'IN' clause.
Any ideas why this is much faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能尝试使用
INSERTED
表进行常规JOIN
吗?这些子查询的性能通常比子查询好得多:不知道您的所有详细信息,不可能确定这是否有帮助 - 但它绝对值得一试!
Couldn't you just try a regular
JOIN
with theINSERTED
table? Those often perform significantly better than those subqueries:Not knowing all your details, it's impossible to know for sure whether this will help at all - but it's defintely worth a try!