Re-Sequence a set of data in SQL Server

I have a table of values like this:

CREATE TABLE 
(
    Name1 VARCHAR (50),
    Name2 VARCHAR (50),
    Sequence INT
)

In this table I have rows like this

'Bob', 'Jones', 1
'James','Ant', 2

I want the best way to UPDATE (UPDATE SET) sequence based on the order of say the Name2 column, so when re-sequenced the values are:

'James','Ant', 1
'Bob', 'Jones', 2

I am pretty sure this can be done with a ROW_NUMBER OVER() style of CTE but not sure of the exact syntax.

13.10.2009 15:23:45
4 ОТВЕТА
РЕШЕНИЕ

How about something like this:

WITH OrderedByName AS
(
  SELECT Name1, Name2, 
  ROW_NUMBER() OVER(ORDER BY Name2, Name1) as 'RowNum'
  FROM YourTable
)
UPDATE YourTable
SET Sequence = obn.RowNum
FROM OrderedByName obn
WHERE obn.Name1 = YourTable.Name1 
  AND obn.Name2 = YourTable.Name2

Marc

4
13.10.2009 15:27:18

you don't need to use a CTE, a derived table will work, try this:

create table abc 
(
    Name1 VARCHAR (50),
    Name2 VARCHAR (50),
    Sequence INT
)

insert into abc values ('Bob', 'Jones', 1
)
insert into abc values ('James','Ant', 2
)

SELECT * FROM abc ORDER BY Sequence

UPDATE a
    SET Sequence=dt.Rank
    FROM abc a
        INNER JOIN (SELECT
                        Name1, Name2 
                            ,ROW_NUMBER() OVER(ORDER BY Name2, Name1,Sequence) AS Rank
                     FROM abc
                   ) dt ON a.Name1=dt.Name1 AND a.Name2=dt.Name2

SELECT * FROM abc ORDER BY Sequence

OUTPUT:

Name1               Name2    Sequence
------------------- -------- -----------
Bob                 Jones    1
James               Ant      2

(2 row(s) affected)

(2 row(s) affected)

Name1               Name2    Sequence
------------------- -------- -----------
James               Ant      1
Bob                 Jones    2

(2 row(s) affected)
1
13.10.2009 17:20:25

You can update a CTE:

WITH OrderedT AS
(
  SELECT Sequence, 
  ROW_NUMBER() OVER (ORDER BY Name2, Name1) as rn
  FROM T
)
UPDATE OrderedT
SET Sequence = rn;
6
13.10.2009 15:41:08
FYI using SET SHOWPLAN_ALL ON with my sample table and data, this had a TotalSubtreeCost of 0.02465125, while the CTE+UPDATE and my derived table both had 0.0513813, more than twice this UPDATE CTE's
KM. 13.10.2009 15:59:19

In response to KM's solution - MS SQL older than 2005 does not support ROW_NUMBER().

0
13.10.2009 16:03:48