Automatically Update Field in Database

痞子三分冷 提交于 2019-12-04 19:46:15
Tony Andrews

Why do you need to read the T_RIDER_PONY table in the trigger? You will have either inserted or deleted a row, so all the trigger needs to do is look up the pony name in T_PONY and update table T_RIDER, either appending the name to or removing it from TMP_PONYLIST like this

create trigger t_rider_pony_trg 
after insert or delete on t_rider_pony
for each row
begin
   if inserting then
      select pony_name
      into   l_pony_name
      where  pony_id = :new.pony_id;

      update t_rider
      set    tmp_ponylist = tmp_ponylist || ';' || l_pony_name
      where  rider_id = :new.rider_id;
   elsif deleting then
      select pony_name
      into   l_pony_name
      where  pony_id = :old.pony_id;

      update t_rider
      set    tmp_ponylist = ltrim ( 
                               rtrim ( 
                                  replace(';' || tmp_ponylist || ';',
                                          ';' || l_pony_name || ';',
                                          ';'),
                                  ';', ';')
      where  rider_id = :old.rider_id;
   end if;
end;

That update in the delete section is rather unpleasant I admit; it might be preferable to use utilities like apex_util.string_to_table and apex_util.table_to_string to deal with it! See this SO answer for details.

Vincent Malgrat

the information on the column TMP_PONYLIST is redundant (it exists somewhere else). You will get into all sorts of problems to maintain it (No solution will work correctly in a multi-user environment unless there is some sort of locking mechanism).

In a normalized model you would simply drop this column from the physical model. If you need the information, you could use a view, for example with Oracle 11gR2:

CREATE OR REPLACE VIEW rider_v AS
SELECT rider_id, /*...,*/
       (SELECT listagg(p.pony_name, ';') WITHIN GROUP (ORDER BY p.pony_name)
          FROM t_pony p
          JOIN t_rider_pony rp ON (p.pony_id = rp.pony_id)
         WHERE rp.rider_id = r.rider_id) tmp_ponylist
  FROM t_rider r;

See this SO for example of string aggregation before 11gR2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!