SQL使用UPDATE / CASE / WHEN

时间:2015-10-25 21:04:05

标签: ms-access sql-update

希望创建一个Update查询,根据同一个表中另一列的值设置列中的值,例如:

UPDATE mytable
SET field1 = CASE field2
         WHEN field2 = 1 THEN "ASG1"
         WHEN field2 = 2 THEN "ASG2"
         WHEN field2 = 3 THEN "ASG3"
         WHEN field2 = 4 THEN "ASG4"
         WHEN field2 = 5 THEN "ASG5"
         ELSE Field1 (retaining old value)
         END
WHERE field2 IN (1,2,3,4,5)

无论我尝试什么,我一直搞砸了声明

当前和更新形式的数据示例如下:

field1 field2
value    1
value    2
value    3

field1 field2
asg1     1
asg2     2
asg3     3

1 个答案:

答案 0 :(得分:3)

Access SQL不支持CASE ... WHEN。您可以使用Switch表达式代替......

UPDATE mytable
SET field1 = 
    Switch
        (
            field2 = 1, "ASG1",
            field2 = 2, "ASG2",
            field2 = 3, "ASG3",
            field2 = 4, "ASG4",
            field2 = 5, "ASG5"
        )
WHERE field2 IN (1,2,3,4,5)

但是,您可以通过这个更简单的UPDATE ...

获得所需的结果
UPDATE mytable AS m
SET m.field1 = 'ASG' & [m].[field2]
WHERE m.field2 In (1,2,3,4,5);