我有一个名为Site
的表,其中包含Name
,SiteId
和Sequence
列。我想用rownumber填充Sequence
字段。我尝试了以下查询,但它只是不更新记录:
WITH RowNumbers AS
(
select SiteId,
RowNum = row_number() OVER ( order by SiteId )
from [Site]
)
UPDATE s
SET s.[Sequence] = r.RowNum
FROM [Site] as s INNER JOIN RowNumbers as r ON s.SiteId = r.Row
我做错了什么?
答案 0 :(得分:16)
您可以直接更新CTE ......
WITH RowNumbers AS
(
select *,
RowNum = row_number() OVER ( order by SiteId )
from [Site]
)
UPDATE RowNumbers
SET [Sequence] = RowNum
这与可更新视图的工作方式相同。我添加了*
以确保更新的字段通过,然后直接更新。
答案 1 :(得分:3)
您应该加入r.SiteID
,而不是r.Row
WITH RowNumbers AS
(
select SiteId,
RowNum = row_number() OVER ( order by SiteId )
from [Site]
)
UPDATE s
SET s.[Sequence] = r.RowNum
FROM [Site] as s INNER JOIN RowNumbers as r ON s.SiteId = r.SiteID