在 SQL 2008 中使用 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,然后在设置后将其设置为第一个找到的值。
有什么想法吗?
编辑:我需要更新汽车表中的多个列。这就是使用 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
I have the following SQL statement where i'm trying to update multiple rows matching a select statement.
UPDATE Cars
SET engineSize = CASE specCode WHEN 1 THEN value ELSE engineSize END
FROM Cars
INNER JOIN CarSpecs ON CarsSpecs.carID = Cars.carID
My tables are as follows:
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 relates to a type of specification I want to update in the Cars table (1 being the engine size)
When I run the query it comes back NULL everytime. The way I see it it should find the specCode = 1 and set the engineSize to 1800 then after it's set it just sets it to the first found value.
Any ideas?
Edit: I need to update multiple columns in Cars table. That's the reason for using CASE, ie:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要更新多个列,在您的情况下,您需要多个联接(如 Martin 所描绘的)
使用 OUTER 联接,并非每辆车都存储每个规格。
To update multiple columns, in your case you need multiple joins (as sketched by Martin)
Use OUTER joins of not every spec is stored for each car.
如果马丁的解决方案不起作用(当它运行三次时),您也可以立即执行...尽管有点复杂:
In case that Martin's solution does not work (when it is run three times) you could do it also at once ... although a bit more arkward:
ELSE
部分不是强制性的。但如果不存在,则所有未评估的情况都将替换为 NULL。The
ELSE
part is not mandatory. But if it isn't there, all cases not evaluated will be replaced with NULL.