0

我想创建一个更新 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
4

3 回答 3

1

Try something like this

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
于 2013-11-04T10:23:38.727 回答
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)
于 2013-11-04T10:22:40.833 回答
1

你不能这么简单地动态地做到这一点。您必须<conditionRow..>在 WHEN 子句中输入硬编码值:

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
于 2013-11-04T10:33:00.877 回答