sql - Doing UPSERT when row is referenced by a FK -
let's have table of items, , each item, there can additional information stored it, goes second table. additional information referenced fk in first table, can null (if item doesn't have additional info).
table item ( ... item_addtl_info_id integer ) constraint fk_item_addtl_info foreign key (item_addtl_info) references addtl_info (addtl_info_id) table addtl_info ( addtl_info_id integer not null generated default identity ( increment 1 no cache ), addtl_info_text varchar(100) ... constraint pk_addtl_info primary key (addtl_info_id) ) what "best practice" update item's additional info (in ibm db2 sql, preferably)?
it should upsert operation, meaning if additional info not yet exist new record created in second table, if does, updated, , fk in first table not change.
so imperatively, logic:
upsert(item, item_info): case when item.item_addtl_info_id null insert addtl_info (item_info) update item.item_addtl_info_id (addtl_info.addtl_info_id) ^^^^^^^^^^^^^ else update addtl_info (item_info) end my main problem how newly inserted addtl_info row's id (underlined above). in stored proc can request id sequence , store in variable, maybe there more straightforward way. isn't comes time when programming databases?
i mean, i'm not interested in id of addtl_info record long remains unique , referenced properly. using sequences seems bit of overkill me in case.
as matter of fact, upsert operation should part of sql language standard operation (maybe is, , don't know it?)...
the syntax looking is:
select * new table ( insert phone_book values ( 'peter doe','555-2323' ) ) from wikipedia (http://en.wikipedia.org/wiki/insert_%28sql%29)
this how refer record inserted in table.
my colleague called construct "in-place trigger", is...
here first version put compound sql statement:
begin atomic declare addtl_id integer; set addtl_id = (select item_addtl_info_id item item.item_id = xxx); if addtl_id null set addtl_id = (select addtl_info_id new table (insert addtl_info (addtl_info_text) values ('my brand new additional info') ) ); update item set item.item_addtl_info_id = addtl_id item.item_id = xxx; else update addtl_info set addtl_info_text = 'my updated additional info' addtl_info.addtl_info_id = addtl_id; end if; end xxx being equal item id updated - code can inserted sproc, , xxx can converted input parameter.
i tried using merge into, couldn't figure out syntax updating table different specified target.
Comments
Post a Comment