更新表中的订单列但保持订单

时间:2014-09-23 14:20:44

标签: sql-server sql-update

我有一张桌子

id | title | F_ID  | order
----------------------------
1  | test 1| 1     | 44
2  | test 3| 1     | 3
3  | test 4| 1     | 1
4  | test 5| 2     | 1

我想将订单列更新为+10,因为所有行都有F_ID 1但保留订单

结果需要

id | title | F_ID  | order
----------------------------
1  | test 1| 1     | 30
2  | test 3| 1     | 20
3  | test 4| 1     | 10
4  | test 5| 2     | 1

我可以将要更新的所有行插入临时表 然后循环行并通过[id]更新真实表中的每一行。

也许还有更好的选择?

2 个答案:

答案 0 :(得分:4)

我认为这应该有效:

SQL Fiddle

MS SQL Server 2008架构设置

create table test (id int, title  varchar(49), F_ID int, [order] int)
insert test values 
(1  , 'test 1', 1, 44),
(2  , 'test 3', 1, 3),
(3  , 'test 4', 1, 1),
(4  , 'test 5', 2, 1)

查询1

update test
set [order] = new_order
from test t
inner join (
    select 
       id, 
       new_order = ROW_NUMBER() over (partition by f_id order by [order]) * 10
    from test t
    where f_id = 1
) t2 
on t.id = t2.id

<强> Results

查询2

select * from test

<强> Results

| ID |  TITLE | F_ID | ORDER |
|----|--------|------|-------|
|  1 | test 1 |    1 |    30 |
|  2 | test 3 |    1 |    20 |
|  3 | test 4 |    1 |    10 |
|  4 | test 5 |    2 |     1 |

答案 1 :(得分:0)

那么可能有一个更好的解决方案,但你可以通过使用递归CTE来尝试这个。

;WITH updCTE
AS 
(
    SELECT 30 AS YourOrder, 1 AS id

    UNION ALL

    SELECT YourOrder - 10 AS YourOrder, id + 1 AS id
    FROM updCTE
    WHERE YourOrder > 1
)
UPDATE YourTable
SET [order] = YourOrder
FROM updCTE
JOIN YourTable ON updCTE.id = YourTable.id
WHERE YourTable.F_ID = 1
ORDER BY YourTable.id