使用ROW_NUMBER()将CTE和行号更新为序列或TSQL更新查询

时间:2012-08-24 13:56:15

标签: sql sql-server-2008 tsql

我有一个名为Site的表,其中包含NameSiteIdSequence列。我想用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

我做错了什么?

2 个答案:

答案 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