Izumi
Izumi

Reputation: 571

Oracle Pl/SQL: Trigger after insert on Table1 calling a function for Table2?

I'm rather new to Oracle PL/SQL, so I'm not sure whether it's possible to do something like this:

Two tables - T1 and T2 - T1.id is foreign key referencing T2.id, each table has a sequence; I've written a function that when it's called allows the user to insert new rows in T1 - will call it func1, same for T2 - func2; Also a function that get us the last inserted sequence in a table - getLastSeq(table);

So, now I'm trying to create a trigger after insert on T2 calls func1, allowing the user to write the input info.

CREATE OR REPLACE TRIGGER trig1
AFTER INSERT ON T2
DECLARE
-----?----
BEGIN
----?----
dbms_output.put_line(func1(:col1, :col2));
----?----?
END;

But all my possible attempts to do so die with errors about :col1 not being a bad bind var.

Upvotes: 0

Views: 4189

Answers (2)

Justin Cave
Justin Cave

Reputation: 231741

I'm not quite sure that I understand what you're trying to accomplish.

  1. If you are creating a PL/SQL block that inserts a row, that really ought to be a procedure, not a function. A function is supposed to perform a computation and return a result. A procedure is supposed to do DML.
  2. I'm not sure what you mean by "allowing the user to write the input info". PL/SQL has no facilities to prompt the user for input-- it can only accept input parameters.
  3. I'm not sure that I understand how an insert into a parent table (T2) could ever logically insert a row into a child table (T1). That would imply that T1 is not really a child table which implies that you have some sort of problem with the data model.

If your goal is to pass the newly inserted COL1 and COL2 tables from the row that was just inserted into T2 to the PROC1 procedure, my guess is that you want something like

CREATE OR REPLACE TRIGGER trig_t2
  AFTER INSERT ON t2
  FOR EACH ROW
BEGIN
  proc1( :new.col1, :new.col2 );
END;

It sounds, though, like you may not want to use a trigger at all. If you want to create an order, you'd normally have a procedure that executes multiple INSERT statements rather than trying to insert into the child table from a trigger on the parent. Something like this, for example, is going to be much clearer and much easier to maintain than a trigger-based solution.

CREATE OR REPLACE PROCEDURE create_order( p_order_description IN VARCHAR2 )
AS
BEGIN
  INSERT INTO order( order_id, description )
    VALUES( order_id_seq.nextval, p_order_description );

  INSERT INTO order_ship_status( order_ship_status_id, order_id, status )
    VALUES( order_ship_status_id.nextval, order_id_seq.currval, 'Not Shipped' );
END:

Upvotes: 2

Ollie
Ollie

Reputation: 17548

You have your trigger syntax all wrong.

Read through this link which will give you a better understanding of Oracle triggers and some good examples you can follow.

http://docs.oracle.com/cd/B19306_01/appdev.102/b14251/adfns_triggers.htm

Upvotes: 1

Related Questions