用条件更新oracle中的查询

时间:2014-02-11 05:18:17

标签: sql oracle

我必须根据某些条件更新oracle中的一个表。

它包含三个字段。 Name,Old_Address和New_Address

当New_Address被更改时,我必须将Previous New_Address存储到Old_Address中。 我的表包含一些这样的值:

姓名:Sesuraj,Old_address:Chennai,New_Address:Delhi

现在我想将new_address存储到old_address中,如果新地址被更改

update customer set Name='Siva',old_address=new_address,new_address='Mumbai'

现在的结果是: 姓名:Siva,Old_address:德里,新地址:孟买

现在如果new_address没有改变,我必须停止更新

update customer set Name='Guru',old_address=new_address,new_address='Mumbai'

我想这样说:

姓名:Guru,Old_address:Delhi,new_address:Mumbai

4 个答案:

答案 0 :(得分:1)

我认为对于您想要的输出,您必须再次更新Old_address以在输出中再次获取旧的

update customer set Name='Guru',old_address='Delhi',new_address='Mumbai'

答案 1 :(得分:1)

试试这个:

 update customer set Name='Guru',old_add=(SELECT new_add from customer where cust_id=1),new_add='Jaipur' where cust_id=1 AND new_add<>'Jaipur'

这里“斋浦尔”是您的新地址(用户输入)

答案 2 :(得分:0)

尝试使用以下条件:

update customer set Name='Guru',old_address='Delhi',new_address='Mumbai' 
  where new_address<>'Mumbai'

答案 3 :(得分:0)

您可以在更新中使用CASE来使用正确的值,具体取决于它们是否匹配。

UPDATE customer SET name='Siva',
       new_address='Mumbai',
       old_address=CASE WHEN new_address<>'Mumbai'
                        THEN new_address
                        ELSE old_address END
       WHERE id=1;

请注意,您要更新的值会进入查询2次,一次用于更新new_value,一次用于与old_value进行比较;

An SQLfiddle to test with(已编辑,已被破坏)