How to use ROW_NUMBER() in UPDATE clause? [duplicate]

笑着哭i 提交于 2020-04-10 06:47:05

问题


ROW_NUMBER() is only for used in the SELECT clause in MS SQL Server, but I want to use it for update like the following:

Update MyTab Set MyNo = 123 +  ROW_NUMBER() over (Order By ID)
Where a=b;

then I got Error like,

Windowed functions can only appear in the SELECT or ORDER BY clauses.

How to use ROW_NUMBER() in UPDATE clause?


回答1:


DECLARE @MyTable TABLE
(
    ID INT IDENTITY(2,2) PRIMARY KEY,
    MyNum INT,
    ColA INT,
    ColB INT
);

INSERT  @MyTable (ColA, ColB)
SELECT 11, 11 UNION ALL
SELECT 22, 22 UNION ALL
SELECT NULL, NULL UNION ALL
SELECT 33, NULL UNION ALL
SELECT NULL, 44 UNION ALL
SELECT 55, 66;

UPDATE  UpdateTarget
SET     MyNum = RowNum
FROM
(
    SELECT  x.MyNum, ROW_NUMBER() OVER(ORDER BY x.ID) AS RowNum
    FROM    @MyTable x
    WHERE   x.ColA = x.ColB
) AS UpdateTarget;

SELECT * FROM @MyTable;

Results:

ID          MyNum       ColA        ColB
----------- ----------- ----------- -----------
2           1           11          11
4           2           22          22
6           NULL        NULL        NULL
8           NULL        33          NULL
10          NULL        NULL        44
12          NULL        55          66



回答2:


You can use a CTE:

;WITH RowNbrs AS (
    SELECT  ID
            , ROW_NUMBER() OVER (ORDER BY ID) AS RowNbr
    FROM    MyTab
    WHERE   a = b
)
UPDATE  t 
SET     t.MyNo = 123 +  r.RowNbr
FROM    MyTab t
        JOIN RowNbrs r ON t.ID = r.ID;



回答3:


I would use a CTE

WITH myUpdate ( myRowNumber )
AS
( 
    SELECT ROW_NUMBER() over (order by ID) As myRowNumber
    FROM MyTab
    WHERE a = b
 ) 

update MyTab 
set MyNo = 123 + myRowNumber
FROM myUpdate

You can test this first though by doing a

select * from myUpdate


来源:https://stackoverflow.com/questions/19124662/how-to-use-row-number-in-update-clause

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