简体   繁体   中英

How to automatically insert foreign key into table after submit in oracle apex?

I have created forms in which the user can enter data. With collections the information is saved and will be inserted in the corresponding tables after the forms are submitted.

Now one column in the table has remained empty and I am not sure how to solve it in APEX.

Namely, the table has a foreign key to another table.

But the ID of this table is generated only after submitting the forms.

Can I solve it, for example, with a trigger that then enters the foreign key into the table after the forms are submitted?

Would it be an after insert trigger like this:

CREATE OR REPLACE TRIGGER INSERT_FK
AFTER INSERT
ON TBL1 
FOR EACH ROW 
begin
  INSERT INTO TBL2
  VALUES (:NEW.STUID);
  EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
        DBMS_OUTPUT.put_line (TO_CHAR (SQLERRM (-20299)));
    WHEN OTHERS
    THEN
        DBMS_OUTPUT.put_line (TO_CHAR (SQLERRM (-20298)));
end;

or is there another better solution for this?

I would not use a trigger for that, but handle this in your application. You can achieve this by using the RETURNING INTO clause. That allows you to reuse the value of an inserted column in the same transaction.If this is in an anonymous pl/sql block in a page process it would be something like this:

DECLARE
  l_id table1.id%TYPE;
BEGIN
  INSERT INTO table1(val) VALUES ('Europe')
    RETURNING id INTO l_id;
  INSERT INTO table2(continent_id, val) VALUES (l_id,'Belgium');
END;
/

In an apex form, you have an option to return the primary key into a page item after insert/update so you can use it in other processes if you use the built-in form processing.

This won't work; you'd insert only the :new.stuid column value into TBL2 which "might" succeed (if other columns in tbl2 aren't NOT NULL ), but - all other columns will remain empty.

I guess you should prepare all data while you're still in Apex (ie fetch primary key for tbl1 and - at the same time - use it as a foreign key value for tbl2 ). Otherwise, there's no way to populate that information later because there's no other relation between these two tables (if there were, you wouldn't need the foreign key column, would you?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM