如何一次更新包含值列表的表?

时间:2010-06-11 15:39:26

标签: tsql sql-server-2008

我有

update NewLeaderBoards set MonthlyRank=(Select RowNumber() (order by TotalPoints desc) from LeaderBoards) 

我试过这种方式 -

(Select RowNumber() (order by TotalPoints desc) from LeaderBoards) as NewRanks 
 update NewLeaderBoards set MonthlyRank = NewRanks

但它对我不起作用。任何人都建议我如何以这种方式进行更新..

1 个答案:

答案 0 :(得分:2)

您需要使用WITH语句和完整的CTE:

;With Ranks As
    (
    Select PrimaryKeyColumn, Row_Number() Over( Order By TotalPoints Desc ) As Num
    From LeaderBoards
    )
Update NewLeaderBoards
Set MonthlyRank = T2.Num
From NewLeaderBoards As T1
    Join Ranks As T2
        On T2.PrimaryKeyColumn = T1.PrimaryKeyColumn