我想创建一个更新sql语句,可以使用多个条件更新多行,每行依赖于不同的条件,如下所示:
UPDATE tableName
SET row1_field1=newValue1, Row1_field2=newValue2
WHERE row1_condition1=condition1
AND SET row2_field1=newValue1, row2_field2=newValue2 WHERE row2_condition1=condition1
AND SET row3_field1=newValue1, row3_field2=newValue2 WHERE row3_condition1=condition1
答案 0 :(得分:1)
为此你应该使用CASE UPDATE。网上有很多例子可供使用。
例如:
update table set
columnx = (case when condition then new_valuex else columnx end),
columny = (case when condition then new_valuey else columny end)
答案 1 :(得分:1)
尝试这样的事情
UPDATE tableName
SET row1_field1=case when row1_condition1=condition1 then newValue1 end,
Row1_field2=case when row1_condition1=condition1 then newValue2 end,
row2_field1=case when row2_condition1=condition1 then newValue1 end ,
etc
答案 2 :(得分:1)
你不能动态地这么做。你必须在WHEN子句的<conditionRow..>
中加上一个硬编码值:
UPDATE tableName
SET field1 = CASE WHEN condition = <conditionRow1_field1> THEN newValue1
WHEN condition = <conditionRow2_field1> THEN newValue2
...
ELSE field1 END,
field1 = CASE WHEN condition = <conditionRow1_field2> THEN newValueRow1_field2
WHEN condition = <conditionRow2_field1> THEN newValueRow2_field2
...
ELSE field2 END