在 Update 语句中使用子查询

发布于 2024-07-17 03:07:32 字数 368 浏览 6 评论 0原文

我在删除时触发的触发器中有以下 SQL 语句:

UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= SortOrder)

我的问题是最后一个 SortOrder 引用了 Deleted 表,而不是 bk2_InfoPages< /代码>表。 我不允许向 bk2_InfoPages 表添加别名,因为它是一个 UPDATE 语句 - 那么我应该怎么做?

I have the following SQL statement in a trigger that fires on deletion:

UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= SortOrder)

My problem is that the very last SortOrder refers to the Deleted table and not to the bk2_InfoPages table. I am not allowed to add an alias to the bk2_InfoPages table because it's an UPDATE statement - so what should I do instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

愚人国度 2024-07-24 03:07:32
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= bk2_InfoPages.SortOrder)
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= bk2_InfoPages.SortOrder)
如此安好 2024-07-24 03:07:32

这应该可行:

UPDATE b
SET SortOrder = SortOrder - 
  (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= b.SortOrder)
from bk2_InfoPages b

您必须为表添加别名才能执行子查询,例如:

-- this executes fine 
create table #t ( t int)

update t 
set t = (select count(*) from #t t1 where t.t = t1.t)
from #t t

This should work:

UPDATE b
SET SortOrder = SortOrder - 
  (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= b.SortOrder)
from bk2_InfoPages b

You have to alias your table to do sub queries, for example:

-- this executes fine 
create table #t ( t int)

update t 
set t = (select count(*) from #t t1 where t.t = t1.t)
from #t t
慢慢从新开始 2024-07-24 03:07:32

希望这会起作用!

UPDATE bk2_InfoPages
SET SortOrder = SortOrder - subquery.c
FROM (
SELECT SortOrder, COUNT(*) AS c
FROM Deleted d
GROUP BY SortOrder
) AS subquery
WHERE subquery.SortOrder <= bk2_InfoPages.SortOrder;

Hope this would work!

UPDATE bk2_InfoPages
SET SortOrder = SortOrder - subquery.c
FROM (
SELECT SortOrder, COUNT(*) AS c
FROM Deleted d
GROUP BY SortOrder
) AS subquery
WHERE subquery.SortOrder <= bk2_InfoPages.SortOrder;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文