在Update语句中使用子查询

时间:2009-04-19 01:26:31

标签: sql-server subquery sql-update

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

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

我的问题是最后一个SortOrder引用了Deleted表而不是bk2_InfoPages表。我不允许在bk2_InfoPages表中添加别名,因为它是UPDATE语句 - 所以我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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