优化问题:将触发器 INSERTED 或 DELETED 行复制到表变量中

发布于 2024-10-01 19:00:16 字数 457 浏览 1 评论 0原文

我一直遇到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘羡 2024-10-08 19:00:16

您不能尝试使用 INSERTED 表进行常规 JOIN 吗?这些子查询的性能通常比子查询好得多:

SELECT x 
FROM y 
INNER JOIN INSERTED i ON y.x = i.x

不知道您的所有详细信息,不可能确定这是否有帮助 - 但它绝对值得一试!

Couldn't you just try a regular JOIN with the INSERTED table? Those often perform significantly better than those subqueries:

SELECT x 
FROM y 
INNER JOIN INSERTED i ON y.x = i.x

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文