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?
You cannot use the NAME column to sort! UPDATE (SELECT name, order_id FROM test1 ORDER BY order_id) SET order_id = ROWNUM; Does not produce the expecting result because the order by is not used.
The Row_Number function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition specified in the OVER clause. It will assign the value 1 for the first row and increase the number of the subsequent rows. OVER - Specify the order of the rows.
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.
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;
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With