2014-09-23 73 views
1

我有一个表的更新次数列,但维持秩序

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]更新真实表中每一行的所有行。

也许有更好的选择?

+0

这样的事情可能会工作http://stackoverflow.com/questions/8401552/sql-increment-a-number技巧eems是SET x = X + 10 – Terry 2014-09-23 14:25:33

+0

不,我需要给一个全新的数字不会增加它 – eyalb 2014-09-23 14:35:20

+0

您的示例没有意义。如果您添加+10订单,则F_ID = 1。在你的例子中,第一列下降了14,第二列上升了17,第三列上升了9。 – Arun 2014-09-23 14:39:53

回答

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 | 
+0

作品完美! – eyalb 2014-09-23 14:54:52

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 
+0

我的ID不是从1开始加1,它可以是任何数字 – eyalb 2014-09-23 14:47:26