2017-04-07 62 views
0

我有一個包含父表記錄子集的表。 每個子集都有一個存儲在[rank]字段中的訂單。 我需要根據字段otherRank中保存的新訂單更新此表中特定子集的此字段。T-SQL - 通過Row_Number()更新記錄的子集

執行以下操作蓋它:

update mytable t1 set 
[rank] = t2.new_rank_num 
from (select t2.id, new_rank_num = row_number() over (order by t2.otherRank) 
    from mytable t2 where t2.parentID = 628) t2 
where t1.id = t2.id 

,或者將我需要:

update mytable t1 set 
[rank] = t2.new_rank_num 
from (select t2.id, new_rank_num = row_number() over (order by t2.otherRank) 
    from mytable t2 where t2.parentID = 628) t2 
where t1.id = t2.id and t1.parentID = 628 

我的具體問題是,我不希望任何的parentID 628

的職權範圍之外的更新

編輯 試圖運行此命令時出現錯誤:

附近t1 不正確的語法不正確的語法附近t2

所以我想語法必須是:

update mytable set 
    [rank] = t2.new_rank_num 
    from (select id, new_rank_num = row_number() over (order by otherRank) 
from mytable where parentID = 628) t2 
where id = t2.id and parentID = 628 

編輯2

OK,我SqlZim推薦使用CTE解決方案。 它看起來像這樣:

;with cte as (
    select t2.id, new_rank_num = row_number() over (order by t2.otherRank) 
    from mytable t2 where t2.parentID = 628 
) 

update t1 set 
    [rank] = t2.new_rank_num 
from mytable t1 
inner join cte t2 on t1.id = t2.id 
+2

會發生什麼事,當你嘗試了嗎? –

+0

我承認沒有嘗試過,因爲我主要需要一些關於查詢語法的建議。 – scgough

+0

我沒有看到任何明顯的語法錯誤。如果它給出了預期的結果,那就去吧。 –

回答

3

我更喜歡使用common table expression (cte)做這樣的事情:

;with cte as (
    select * 
    , new_rank_num = row_number() over (
     partition by ParentId 
     order by otherRank 
     ) 
    from mytable 
) 
update cte 
set [rank] = new_rank_num 
where ParentID = 628; 

如果您想預覽運行更新前的變化,只是改變上述的select而不是update。請注意,只有cte之後的第一條語句才能使用cte。

+0

謝謝我使用CTE解決方案 - 請參閱更新問題 – scgough

0

您也可以更新視圖,而不僅僅是表格。

試試這個:

UPDATE T 
SET [rank] = [new_rank_num] 
FROM (
    SELECT 
     [rank]   = [rank], 
     [new_rank_num] = row_number() over (order by otherRank) 
    FROM mytable 
    WHERE parentID = 628 
) T