I have a table named Site
with columns Name
, SiteId
and Sequence
. I would like to fill the Sequence
field with the rownumber. I've tried the following query, but it just doesn't update the records:
WITH RowNumbers AS
(
select SiteId,
RowNum = row_number() OVER ( order by SiteId )
from [Site]
)
UPDATE s
SET s.[Sequence] = r.RowNum
FROM [Site] as s INNER JOIN RowNumbers as r ON s.SiteId = r.Row
What am I doing wrong?
> Is it possible to use Row_Number() function in an UPDATE statement? Yes.
CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE a view, as part of the view's SELECT query.
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 update CTE and it will update the base table. Here is the script which you should execute all together.
You can update the CTE directly...
WITH RowNumbers AS
(
select *,
RowNum = row_number() OVER ( order by SiteId )
from [Site]
)
UPDATE RowNumbers
SET [Sequence] = RowNum
This works in the same way as an updatable view. I added *
to ensure the the updated field comes through, and then updated it directly.
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