I have two tables with same schema , and primary key as noc for both,
whenever insert is made in table 1 , its noc must be checked in TABLE2, if exist then complete row must be compared and if there is any difference an exception must be raised .
and if noc does not exist in TABLE2 then simple insertion must follow
this is my trigger function
CREATE OR REPLACE FUNCTION ac_val()
RETURNS trigger AS
$BODY$
BEGIN
IF NEW.acop IS NULL THEN
INSERT INTO exception_detail( noc,exception)
VALUES (new.noc,'number cannot be empty');
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
this is my trigger
CREATE TRIGGER acut_val
AFTER INSERT OR UPDATE
ON acut
FOR EACH ROW
EXECUTE PROCEDURE ac_val();
this is perfectly ok for one table,
but now according to requirement on every insert it must check if noc exists in other table, TABLE2 ,
if exist then comparison must be made, otherwise insertion
I think I can not perform that check on each insert because data to be inserted in acuit is to be copied from csv, and that will require copy from csv, and if i do copy it gives error u must be super user, but if i copy from console its ok.
So can i do something like after data is copied in acuit making a check row by row
SELECT q1.* FROM acut q1
INNER JOIN TABLE2 q2 ON (q1.noc = q2.noc);
it will give records of acut which exists in TABLE2
and then
foreach row of above output{
if (q1.name != q2.name)
Do something ;
if (q2.address < q1.address)
Do something ;
}
The simplest solution I can think of is to use a trigger on
table1.Don’t use the trigger to check uniqueness because you can’t see uncommitted data from other users.
Instead use the trigger to
INSERTthe data intotable2— which should have a unique constraint on all the columns you want to check.If you insert data into table1 that already exists in table2, the unique constraint on table2 will be violated, raising an exception which you can catch in your front end.
The big advantage to this approach is that it will also work correctly for multi-user situations where your transaction can’t see uncommitted data in table2 but the DBMS will still prevent the insert from continuing (the transaction will hang until the other transaction either
commits orrollbacks).