SQL UPDATE row Number

假如想象 提交于 2019-12-06 14:24:40

You have to rewrite it using UPDATE FROM, the syntax is just a bit bulky:

UPDATE serviceClustersNew
FROM
 (
   SELECT text_id,
      (SELECT MAX(ID) FROM serviceClusters) +
      ROW_NUMBER() OVER (ORDER BY Text_ID) AS newID 
   FROM serviceClustersNew
 ) AS src
SET ID = newID
WHERE serviceClustersNew.Text_ID = src.Text_ID

You are not dealing with a lot of data, so a correlated subquery can serve the same purpose:

UPDATE serviceClustersNew 
    SET ID = (select max(ID) from serviceClustersNew) +
             (select count(*)
              from serviceClustersNew scn2
              where scn2.Text_Id <= serviceClustersNew.TextId
             )

This assumes that the text_id is unique along the rows.

Apparently you can update a base table through a CTE... had no idea. So, just change your last UPDATE statement to this, and you should be good. Just be sure to include any fields in the CTE that you desire to update.

;WITH cte_TEST AS 
( SELECT 
    ID,
    ID+ROW_NUMBER() OVER (ORDER BY TEXT_ID) AS RowNumber FROM serviceClustersNew)
UPDATE cte_TEST 
SET cte_TEST.ID = cte_TEST.RowNumber

Source: http://social.msdn.microsoft.com/Forums/sqlserver/en-US/ee06f451-c418-4bca-8288-010410e8cf14/update-table-using-rownumber-over

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!