views:

174

answers:

4

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.

+2  A: 

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

marc_s
A: 

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)
KM
+4  A: 

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;
Remus Rusanu
+1, that is slick!
KM
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
A: 

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

Rkand
doh! good catch!
KM