我要更新一个表的数据
例:表A,里面有3个字段a1,a2,a3
现在用一个update的语句更新了a1的值,怎么可以做到自动更新a3的值,a3=a2-a1

解决方案 »

  1.   

    用2个update不行吗?你这两个行为,明显有先后顺序的啊。
      

  2.   

    除了2个update或者使用触发器,还有其他好的方法吗?
      

  3.   

    -- Oracle 11g中,只要创建一个a3的虚拟字段就可以啦,无需触发器实现,
    -- Oracle 10g中,要用触发器实现:
    create table tt(
    a1 number(18,0),
    a2 number(18,0), 
    a3 number(18,0)
    );CREATE OR REPLACE TRIGGER trig_tt
    BEFORE INSERT ON tt
    FOR EACH ROW
    BEGIN
       SELECT :NEW.a2-:NEW.a1 INTO :new.a3 FROM dual;
    END;
    /insert into tt(a1,a2,a3)
    values(1,9,14);select * from tt;
      

  4.   

    create table tt(
    a1 number(18,0),
    a2 number(18,0), 
    a3 number(18,0)
    );CREATE OR REPLACE TRIGGER trig_tt
    BEFORE INSERT OR UPDATE ON tt
    FOR EACH ROW
    BEGIN
       SELECT :NEW.a2-:NEW.a1 INTO :new.a3 FROM dual;
    END;
    /insert into tt(a1,a2,a3)
    values(1,9,14);select * from tt;
      

  5.   

    eygle@SZTYORA> CREATE OR REPLACE TRIGGER trig_tt
      2  BEFORE INSERT OR UPDATE ON tt
      3  FOR EACH ROW
      4  BEGIN
      5     SELECT :NEW.a2-:NEW.a1 INTO :new.a3 FROM dual;
      6  END;
      7  /触发器已创建eygle@SZTYORA>
    eygle@SZTYORA> insert into tt(a1,a2,a3)
      2  values(1,9,14);已创建 1 行。eygle@SZTYORA>
    eygle@SZTYORA> select * from tt;        A1         A2         A3
    ---------- ---------- ----------
             1          9          8eygle@SZTYORA> update tt set a2=11;已更新 1 行。eygle@SZTYORA> commit;提交完成。eygle@SZTYORA> select * from tt;        A1         A2         A3
    ---------- ---------- ----------
             1         11         10
      

  6.   


    ----写个触发器就可以了
    SQL> 
    SQL> create or replace trigger onetable_trigger
      2    before update of a1 on onetable
      3    for each row
      4  begin
      5    :new.a3 := :new.a2 - :new.a1;
      6  end
      7  ;
      8  /Trigger createdSQL> insert into onetable values(1,2,3);1 row insertedSQL> commit;Commit completeSQL> update onetable set a1=1;1 row updatedSQL> commit;Commit completeSQL> select * from onetable;        A1         A2         A3
    ---------- ---------- ----------
             1          2          1SQL> 
      

  7.   

    其实不是很明白你的需求
    既然你可以update      a1那么也就可以  比如更新a1=50
    update table  set a1=50, a3=a2-50 where 
    干嘛 一定要去分隔操作
      

  8.   

    楼主 你试试这条语句update 表名 set a1 = 值,a3 = a2 - a1 where 条件语句