在SQL 2008中使用CASE更新多行

时间:2010-02-28 14:13:43

标签: sql join sql-update case

我有以下SQL语句,我正在尝试更新与select语句匹配的多行。

UPDATE Cars
SET engineSize = CASE specCode WHEN 1 THEN value ELSE engineSize END
FROM Cars
INNER JOIN CarSpecs ON CarsSpecs.carID = Cars.carID

我的表格如下:

Cars

carID   engineSize ...
1       0
2       0

CarSpecs

carID   specCode    value
1       1           1800
1       2           Blue
1       3           Petrol
2       1           2200
2       2           Green
2       3           Petrol

specCode涉及我想在Cars表中更新的一种规范(1是引擎大小)

当我运行查询时,它每次都会返回NULL。我看到它的方式应该找到specCode = 1并将engineSize设置为1800然后在设置之后将其设置为第一个找到的值。

有什么想法吗?

修改:我需要更新Cars表中的多个列。这就是使用CASE的原因,即:

UPDATE Cars 
SET engineSize = CASE specCode WHEN 1 THEN value ELSE engineSize END,
colour = CASE specCode WHEN 2 THEN value ELSE colour END
FROM Cars
INNER JOIN CarSpecs ON CarsSpecs.carID = Cars.carID

3 个答案:

答案 0 :(得分:3)

要更新多个列,在您的情况下,您需要多个连接(如Martin所示)

UPDATE Cars
SET  engineSize = CarSpecs1.value, colour = CarSpecs2.value
FROM Cars
INNER JOIN CarSpecs CarSpecs1 
    ON CarsSpecs1.carID = Cars.carID AND CarsSpecs1.specCode =1
INNER JOIN CarSpecs CarSpecs2 
    ON CarsSpecs2.carID = Cars.carID AND CarsSpecs2.specCode =2

使用OUTER连接并非为每辆车存储所有规格。

答案 1 :(得分:1)

如果马丁的解决方案不起作用(当它运行三次时)你也可以立刻做到这一点......虽然有点尴尬:

UPDATE Cars
SET Cars.engineSize = (SELECT value FROM CarSpecs WHERE CarSpecs.carId = Cars.carID AND CarSpecs.specCode = 1),
SET Cars.colour = (SELECT value FROM CarSpecs WHERE CarSpecs.carId = Cars.carID AND CarSpecs.specCode = 2),
SET Cars.fuel = (SELECT value FROM CarSpecs WHERE CarSpecs.carId = Cars.carID AND CarSpecs.specCode = 3)
FROM Cars

答案 2 :(得分:1)

UPDATE empsal SET sal =
  CASE WHEN sal BETWEEN 100 AND 500 THEN sal + 400
    WHEN sal BETWEEN 1000 AND 2000 THEN sal + 1000
    else sal
  END

ELSE部分不是强制性的。但如果不存在,则所有未评估的案例都将替换为NULL。