35

ROW_NUMBER()仅用于 中的SELECT子句MS SQL Server,但我想将其用于更新,如下所示:

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

然后我得到了错误,

窗口函数只能出现在 SELECT 或 ORDER BY 子句中。

ROW_NUMBER()inUPDATE子句怎么用?

4

3 回答 3

53

您可以使用 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;
于 2013-10-01T19:57:01.203 回答
33
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;

结果:

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
于 2013-10-01T19:59:26.487 回答
9

我会使用 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

你可以先测试一下

select * from myUpdate
于 2013-10-01T19:58:51.960 回答