动态重新排列SQL Server表中的列值

时间:2019-11-01 12:54:20

标签: tsql sql-server-2017

我有一个用于用户技能的SQL Server表,每个用户的优先级顺序如下:

+----+------+----------+----------+
| ID | user | skill    | priority |
+----+------+----------+----------+
| 1  | foo  | swimming | 1        |
+----+------+----------+----------+
| 2  | foo  | running  | 2        |
+----+------+----------+----------+
| 3  | foo  | hunting  | 3        |
+----+------+----------+----------+
| 4  | boo  | swimming | 1        |
+----+------+----------+----------+
| 5  | moo  | swimming | 1        |
+----+------+----------+----------+
| 6  | moo  | running  | 2        |
+----+------+----------+----------+

当其中一项技能的优先级值更改时,如何编写SQL代码以重新排列用户所有技能的优先级列值(整数)?

例如:对于用户“ foo”,我将“游泳”技能的优先级从(1)更改为(2);更新语句还必须以动态方式更改该用户的所有其他技能的优先级。

因此,在该示例中,“游泳”将是优先级(2)而不是(1),跑步将是(1)而不是(2),其他将保持不变。

1 个答案:

答案 0 :(得分:3)

在此答案中,我假设您要使用SQL而不是C#进行此操作。基于该假设,单个事务中的这两个SQL语句将指定技能的优先级提高1。

'Set @User to the required user and @Skill to the required skill.

'Decrease the priority of the user's skill above the specified skill.
UPDATE MyTable
SET    priority = priority + 1
WHERE  user = @User 
AND    priority = (SELECT priority - 1 
                   FROM MyTable 
                   WHERE user = @User
                   AND skill = @Skill)

'Increase the specified skill's priority.
UPDATE MyTable
SET    priority = priority - 1
WHERE  user = @User
AND    skill = @Skill
AND    priority > 1

以类似的方式,这两个SQL语句提高到指定的优先级。

'Set @User to the required user and @Skill to the required skill.
'Set @NewPriority to the new priority.

'Decrease the higher-prioritised skills.
UPDATE MyTable
SET    priority = priority + 1
WHERE  user = @User 
AND    priority >= @NewPriority 
AND    priority < (SELECT priority
                   FROM MyTable 
                   WHERE user = @User
                   AND skill = @Skill)

'Set the specified skill's priority as requested.
UPDATE MyTable
SET    priority = @NewPriority 
WHERE  user = @User
AND    skill = @Skill
AND    priority > 1

这三个SQL语句移动到指定的优先级。

'Set @User to the required user and @Skill to the required skill.
'Set @NewPriority to the new priority.

'Decrease the higher-prioritised skills to
'handle case where new priority is higher.
UPDATE MyTable
SET    priority = priority + 1
WHERE  user = @User 
AND    priority >= @NewPriority 
AND    priority < (SELECT priority
                   FROM MyTable 
                   WHERE user = @User
                   AND skill = @Skill)

'Increase the lower-prioritised skills to
'handle case where new priority is lower.
UPDATE MyTable
SET    priority = priority - 1
WHERE  user = @User 
AND    priority <= @NewPriority 
AND    priority > (SELECT priority
                   FROM MyTable 
                   WHERE user = @User
                   AND skill = @Skill)    

'Set the specified skill's priority as requested.
UPDATE MyTable
SET    priority = @NewPriority 
WHERE  user = @User
AND    skill = @Skill