我在删除时触发的触发器中有以下 SQL 语句:
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= SortOrder)
我的问题是最后一个
SortOrder
指的是Deleted
表而不是bk2_InfoPages
表。我不允许向 bk2_InfoPages
表添加别名,因为它是 UPDATE
语句 - 那么我应该做什么呢?
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= bk2_InfoPages.SortOrder)
这应该有效:
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
希望这会起作用!
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;