在Update语句中使用子查询

问题描述 投票:0回答:3

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

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

我的问题是最后一个

SortOrder
指的是
Deleted
表而不是
bk2_InfoPages
表。我不允许向
bk2_InfoPages
表添加别名,因为它是
UPDATE
语句 - 那么我应该做什么呢?

sql-server subquery sql-update
3个回答
2
投票
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= bk2_InfoPages.SortOrder)

1
投票

这应该有效:

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

0
投票

希望这会起作用!

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;
© www.soinside.com 2019 - 2024. All rights reserved.