INSERT上每行重新计算子查询

时间:2016-06-28 06:49:53

标签: sql sql-server subquery

当我有下表时:

CREATE TABLE Acts ( ParentID int, ActID int, Text nvarchar(255) )
---------------------
1 | 1 | "Hello"
1 | 2 | "Hello again"
2 | 1 | "lol"
2 | 2 | "rofl"

其中ActID是基于ParentID的连续数字。 我需要为每个行子集插入新行,如:

INSERT INTO Acts
SELECT ParentID, (SELECT MAX(ActID) + 1 FROM Acts), Text FROM Acts WHERE Text LIKE 'Hello%'

我得到了

1 | 1 | "Hello"
1 | 2 | "Hello again"
1 | 3 | "Hello"
1 | 3 | "Hello again"
...

我想:

1 | 1 | "Hello"
1 | 2 | "Hello again"
1 | 3 | "Hello"
1 | 4 | "Hello again"

我很快意识到Subquery仅在INSERTS发生之前进行评估,这就是为什么它总是返回相同的Max数​​。有没有办法逐个插入结果,以便子查询可以更新OR以指定子查询需要在每行之后更新?

1 个答案:

答案 0 :(得分:3)

试试这个,它只会获得最大的ActID并在其中添加1,2,3。

INSERT INTO Acts
SELECT ac.ParentID, (SELECT MAX(ac1.ActID) FROM Acts ac1 WHERE ac1.ParentID = ac.ParentID ) + ROW_NUMBER() OVER(partition by ac.ParentID order by ac.ParentID), Text 
FROM Acts ac
WHERE ac.Text LIKE 'Hello%'