Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update with CTE and row-numbers as sequence or TSQL update query with ROW_NUMBER()

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?

like image 821
Kees C. Bakker Avatar asked Aug 24 '12 13:08

Kees C. Bakker


People also ask

Can we use ROW_NUMBER in update query?

> Is it possible to use Row_Number() function in an UPDATE statement? Yes.

Can we use CTE in update statement?

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.

What is ROW_NUMBER () function in SQL?

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.

Does updating CTE update original table?

You can update CTE and it will update the base table. Here is the script which you should execute all together.


1 Answers

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.

like image 132
MatBailie Avatar answered Sep 25 '22 14:09

MatBailie