我有9条记录的表,删除了_id = 1的2条记录:
id | name | index | _id
1 a 1 1
8 b 3 1
9 c 7 1
10 d 4 1
15 e 2 1
16 d 1 2
17 e 2 2
我希望像这样重置_id = 1的索引:
id | name | index | _id
1 a 1 1
8 b 2 1
9 c 3 1
10 d 4 1
15 e 5 1
16 d 1 2
17 e 2 2
我使用此查询
declare @_idCount int = (select count(*) from tbl where _id = 1),
@index int = 1
while(@_idCount > 0)
begin
update tbl
set code = @index
where _id = 1
set @index = @index + 1
set @picCount = @picCount - 1
end
但是此代码使用相同的代码设置所有记录。 我能做些什么来解决它?
答案 0 :(得分:1)
您只需使用ROW_NUMBER
:
WITH CTE AS
(
SELECT id,
name,
[index],
[_id],
new_index = ROW_NUMBER() OVER(PARTITION BY [_id]
ORDER BY [id])
FROM dbo.tbl
)
UPDATE CTE
SET [index] = new_index;