Creating a pseudo foreign key trigger

hi
i want to create a trigger that will act like a foreign key and check whether the value being entered already exists in two separate tables. I want it to not allow entry if the id already exists in: either none of the tables; or both the tables.
I have tried to create the following trigger, it compiles, but doesnt do the job :(
create or replace trigger trig_test1
before insert on TEST3
referencing old as old new as new
for each row
DECLARE
cursor cur_check_test1 is
select PKONE
from TEST1, TEST3
where PKONE = TEST3.PKTHREE;
CURSOR CUR_CHECK_TEST2 IS
SELECT PKTWO
FROM TEST2, TEST3
WHERE PKTWO = TEST3.PKTHREE;
v_key_conflict EXCEPTION;
v_test1_temp varchar2(1);
v_test2_temp varchar2(1);
BEGIN
OPEN cur_check_test1;
FETCH cur_check_test1 into v_test1_temp;
if (((cur_check_test1%FOUND) AND (cur_check_test2%found)) or ((cur_check_test1%notfound) and (cur_check_test2%notfound)))
then close cur_check_test1;
close cur_check_test2;
RAISE v_key_conflict;
else
close cur_check_test1;
close cur_check_test2;
end if;
EXCEPTION
WHEN v_key_conflict then
raise_application_error(-20111, 'parent key constraint violated');
end;
Can someone please help me out. cheers

What business requirement are you trying to meet?
It's going to be difficult to correctly implement this kind of constraint using triggers, because:
1. You will need to handle updates on TEST3, not just inserts.
2. You will need to handle inserts, updates, and deletes on both TEST1 and TEST2.
3. You will need some sort of locking mechanism to prevent concurrent transactions from violating the constraint (because they can't see the changes that other transactions have made but have not yet committed).
In other words, it might be on the order 10 times more complicated to implement this kind of constraint using triggers than you originally thought. Before pursuing the trigger approach further, it might be worth looking into some alternatives. Is the benefit of implementing the constraint worth the effort? Are there some "creative" ways you can use declarative (built-in) constraints instead? Would restructuring your tables help?

Similar Messages

  • Problem creating table with foreign key in SQL Workshop

    Application Express version 2.2.1.00.04
    Get error message "Number of referencing columns/data types must match referenced columns"
    Master table SLS_SUPPLIERS has primary key SLS_ID NUMBER(8,0) and when creating table SLS_PRODUCTS with FK SLS_SLP_ID NUMBER(8,0) using the create table wizard I get the above error.
    The name of the FK is SLP_SLS_FK, key column is SLP_SLS_ID, referenced table is SLS_SUPPLIERS and referenced column is SLS_ID.
    Any help is much appreciated.
    James Edey
    I should add that if I create the table without the foreign key constraint and then create the constraint separately in SQL Workshop then it creates OK. It only fails in the create table wizard dialog.
    Message was edited by:
    edeyje
    Obviously no-one interested in this - just thought it may be a bug in v2.2 that the development team would find useful.
    James
    Message was edited by:
    edeyje

    I replied to the other thread on this too -
    there is a bug on that page when you click Next. If you define more than one fk but then navigate using the links on the process chart on the left (Constraints, Confirm, etc), the page works fine. We do have a bug on this now and I just added the notes I will need to get this fixed in 3.1 (I have already assigned it to me - must have some rogue validation that fires on next).
    Sorry it took so long for this to get noticed - I am glad I checked the forum this morning -
    -- Sharon

  • ADF Toplink Create Row with foreign key

    Hello,
    I'd like to create a new row in a table that has a required one-to-one mapping relationship (foreign key). I've created an edit form by dragging the return node of a readQuery. The columns holding foreign key values aren't added to the page(because of 1-1 relationship) and when I commit the changes errors are raised.
    How do I pass the foreign key to the ADF Toplink framwork to include in the insert statement.

    TopLink's persistence model is based around relationships, which represent FKs. To have these FKs properly populated you need to create the corresponding object relationships.
    To do this you need to create a data action that will invoke a method on your class passing in the object you want to create the relationship with. There is currently an issue where ADF will not allow you to easily drop a set method onto an action. You will need to create a method on your bean that does not start with 'set'.
    In the demos I have done I have added a method like 'populateAddress(Address)' that internally calls the set method. This populate method will show up on the data control palette and you can then drop it on the action in your page flow.
    One additional tip: To access the object you want to pass in you will need to extend the default expression that reflects the current selected row in the iterator to have '.dataProvider' appended. This accesses the persistent object within row container.
    If you are still struggling please contact me through the email address in my forum profile.
    Doug

  • Syntax for creating foreign key across users in a database

    There are two user present A,B.They are granted all privileges.Now in USER A, there is a table PARENT whose primary key is PARENT_NO.In USER B I have created a table CHILD whose primary key is CHILD_NO.
    In the CHILD table of USER B, I want to create a foreign key relation to the PARENT table of USER A.For this I have created a column CHILD_PARENT_NO in the CHILD table.If anybody knows the syntax please post the syntax for creating the required foreign key relationship?

    Please post your code. Cut'n'paste from SQL*Plus like this...
    SQL> conn a/a
    Connected.
    SQL> desc t1
    Name                                      Null?    Type
    COL1                                               NUMBER
    COL2                                               VARCHAR2(10)
    SQL> grant references on t1 to b;
    Grant succeeded.
    SQL> conn b/b
    SQL> create synonym a_t for a.t1;
    Synonym created.
    SQL> alter table test add constraint fk foreign key (n) references a_t(col1);
    Table altered.
    SQL> Note that Oracle will translate the synonym anyway...
    SQL> select constraint_name, r_owner, r_constraint_name
      2  from  user_constraints
      3  where table_name = 'TEST'
      4  /
    CONSTRAINT_NAME R_OWNER R_CONSTRAINT_NAME
    FK              A       T1_PK
    SQL> By the way, this ...
    GRANT ALL PRIVILEGES TO B;... is a mindbendingly unsafe way of proceeding. In real life you would have given user B the power to utterly destroy your database. It's always easier to start with good habits than to break bad ones so please get used to granting only the minimum set of privileges necessary.
    Cheers, APC

  • Foreign Keys for a Logical Table

    Hi All,
    I want to know in which scenarios we create the Foreign Keys for a Logical Table. Once we create the foreign key for the logical table, does it mean that it will automatically override if any joins are there.
    Physical Table A, B ( no physical joins)
    Logical Table A, B (logical join B(Dim)-->A(Fact))
    created the foreign key in logical table A with B .(A.1=B.1)
    Will the rpd generate sql with A.1=B.1 join condition for reports.
    I tried to create the logical foreign key for logical table A, I could not see any corresponding table option.Here is its snapshot
    http://tinypic.com/r/jq1gkz/6
    Thanks,
    Virat

    In general when we go complex joins in Physical layer we go for Logical foreign key joins in BMM layer, best examples is SCD Type-II.
    Physical Table A, B ( no physical joins)
    -->You need to have a physical join so that this can be override by BMM layer
    created the foreign key in logical table A with B .(A.1=B.1) Will the rpd generate sql with A.1=B.1 join condition for reports.
    -->Yes you can see this join in BI Physical query.
    I tried to create the logical foreign key for logical table A, I could not see any corresponding table option.Here is its snapshot
    -->2 cases: 1)You need to delete existing logical joins 2) You might not have join in physical layer.
    Hope this helps
    Let me know for issues
    Edited by: Srini VEERAVALLI on Jan 18, 2013 1:29 PM
    BTW: You got very good name, why dont you update in your profile to see your name instead of some number
    Edited by: Srini VEERAVALLI on Jan 18, 2013 1:29 PM

  • Optional Composite Foreign Key

    The tool doesn't seem to be handling this correctly when some of the columns are mandatory and others are nullable. I have a composite foreign key where one column is part of the primary key and the other is not. In the Columns properties of the Table dialog, it shows the column that is part of the primary key as mandatory. But on the diagram, the "red dot" indicator is missing. It also give me an error on the Foreign Keys properties when I click OK or Apply.

    No, You cant get a composite keys based on two different primary keys. Reason for this can be like unique index is being used when we create any primary key. When we create a composite primary key, one index is created for the two fields and thus one index store the values for two columns involved in the composite primary key and these values are stored in pairs. So when any foreign key references this composite primary key, it will match the data in pairs as it is stored in the index(unique index).
    Now when we say to create a composite foreign key based on two different primary keys , we are taking into account two indexes for two different fields. So there is no pairing in these two indexes. So when we will create foreign key using this, it will not get a pair of values or we can say oracle cant get us consistent pair of values from two indexes. So maintaining integrity will not be possible.
    Yes you can create two foreign keys on one column which can refer two different primary keys.
    Regards

  • Composite Foreign Key

    Dear All
    please correct this syntax for composite foreign key.
    Ater Table emp_pays
    Add Constraints emp_pt_fk Foreign Key(emp_id,pt_id) Referenes emp(emp_id),pay_type(pt_id);
    Thanks in advances
    Regards,

    No, You cant get a composite keys based on two different primary keys. Reason for this can be like unique index is being used when we create any primary key. When we create a composite primary key, one index is created for the two fields and thus one index store the values for two columns involved in the composite primary key and these values are stored in pairs. So when any foreign key references this composite primary key, it will match the data in pairs as it is stored in the index(unique index).
    Now when we say to create a composite foreign key based on two different primary keys , we are taking into account two indexes for two different fields. So there is no pairing in these two indexes. So when we will create foreign key using this, it will not get a pair of values or we can say oracle cant get us consistent pair of values from two indexes. So maintaining integrity will not be possible.
    Yes you can create two foreign keys on one column which can refer two different primary keys.
    Regards

  • Logical foreign key

    Hi All,
    I apologize to bring similar question. .
    I am able to create the logical foreign key for logical table A with new joining condition (A.2=B.2) (2 is calculated logical column).
    However there still exist Physical foreign key join with old condition (A1.=B.1). When I deploy this rpd, the report generates sql with (A1.=B.1) join condition.
    Then,I removed this Physical foreign key join in rpd,and got a warning' logical dimension B has a source that does not join with any fact table' in consistency check.
    Still after deploying this rpd , I am getting error [nQSError: 14025] No fact table exists at the requested level of detail: in report.
    I am missing anything.The logical foreign key has correct join condition still it is not over riding the physical join.
    Thanks for going through this question,
    http://tinypic.com/r/2qiwmrr/6

    Based on your comments I'm looking at documentation:
    I found a Note: A logical key for a fact table must be made up of the key columns that join to the attribute tables. Logical foreign key joins may be needed if the Oracle BI Server is to be used as an ODBC data source for certain third-party query and reporting tools.
    I need to see why ODBC, and unlike the Logical Foreign key join is not overriding join Physical layer.
    Btw: Since you want to go with a join using defined logical column, can you use the same expression in Physical join using expression builder?
    This should work.
    EX: T43770.DEPARTMENT_ID = case when T43764.DEPARTMENT_ID > 10 then T43764.DEPARTMENT_ID else 0 end
    Edited by: Srini VEERAVALLI on Jan 18, 2013 4:52 PM

  • ADF-Master detail-Foreign key generated By Trigger won't propaget to Detail

    Hi All,
    We have Master-Detail Table where Master table key is generated by DB.
    And this key act as Foreign key in detail table.When we Creates Master Table records and commit it .It gets saved correctly But when we navigate to Create Detail record (Cretae button is taken from Detail) It opens in Create mode but does n't poppulate Foreign Key.
    Can anybody plz explain..
    Regards
    Yogesh

    Hi Frank,
    Thanks for your reply.I don't know "the ADF Business Components tester "
    what is this ?
    I was able to solve my problem by making "Refresh after insert " Check box selected in Entity object.Now it is generating Master Key and also i am getting it in Detail.
    But now problem is, Can we make details record in insert mode by 'Create opration' under Master View.My requirment is insert two records in detail table in background while inserting record in master.Where relationship is maintained by foreign key which generated by trigger.
    I want master and detail create form on same page where i will make details from Rendering False i.e both should be in Create mode (Accesser should not retrive record).
    In Short
    ADF-BC Master Detail - Detail Record insert in Back ground on the same page
    Thanks in Adv
    RHY

  • Before delete trigger and foreign key relationship

    Hi,
    I am analysing one database for migration. On one parent table there is before delete trigger , to delete records from child. Also there is foreign key relationship on child table for this parent table.
    When I am deleting a row from parent, message gets displayed as "there are child records found."
    I would like to know, if there is foreign key relatioship then delete trigger on parent does't work, what is exactly happening?

    Could you post that trigger code and the Oracle version as well?
    With basic assumptions, I can't reproduce what you have stated here.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL> create table parent (id number primary key);
    Table created.
    SQL> create table child (id number);
    Table created.
    SQL> alter table child add constraint fk_parent foreign key (id) references parent;
    Table altered.
    SQL> create or replace trigger bdr_parent
      2  before delete on parent
      3  for each row
      4  begin
      5  delete from child where id = :old.id;
      6  end;
      7  /
    Trigger created.
    SQL> insert into parent (id) values (1);
    1 row created.
    SQL> insert into child (id) values (1);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> delete from parent where id = 1;
    1 row deleted.
    SQL> select * from parent;
    no rows selected
    SQL> select * from child;
    no rows selected
    SQL> rollback;
    Rollback complete.
    SQL> alter table child drop constraint fk_parent;
    Table altered.
    SQL> alter table child add constraint fk_parent foreign key (id) references parent on delete cascade;
    Table altered.
    SQL> delete from parent where id = 1;
    delete from parent where id = 1
    ERROR at line 1:
    ORA-04091: table SCOTT.CHILD is mutating, trigger/function may not see it
    ORA-06512: at "SCOTT.BDR_PARENT", line 2
    ORA-04088: error during execution of trigger 'SCOTT.BDR_PARENT'
    SQL>

  • Subquery in IF statement in trigger, without using foreign keys

    Hello,
    I'm investigating ways of writing a subquery in an IF statement, which is placed inside a trigger.
    I wanna write smth like IF (:new.jazz not in (select goldies from T where ... )) etc. I don't know whether the fact that the IF is in a trigger adds some additional restrictions. (Does it?)
    So far I found the solution described here: SubQuery Comparison in If Statement which I find a bit tacky, I could have the 'cooleststarinthegalaxy' instead of 1 and seems you need to do extra light, but still extra lifting.
    I also read about the possibility of using MERGE, which I'm currently researching.
    Is there any other way?
    Thanks
    Edited by: BluShadow on 14-Nov-2012 13:37
    fixed link
    Edite by me: the question is how (if possible) to do this without a foreign key.
    Edited by: questioningq12 on Nov 14, 2012 6:11 AM
    Edited by: questioningq12 on Nov 14, 2012 6:13 AM

    Hi,
    questioningq12 wrote:
    Say I have tables A(namea varchar(10)), B(nameb varchar(10)), and B contains tuples ('1stname','2ndname').
    I wrote a trigger before insertion, for each row, on table A. For a tuple t to be inserted, it should check whether t.namea is in the set of values nameb from B.
    E.g., INSERT INTO A VALUES('1stname') should work. But INSERT INTO A VALUES ('3rdname') should fail. You can use a foreign key constraint for that.
    If the tables already exist, and b.nameb is declared as UNIQUE (or PRIMARY KEY), then you can say:
    ALTER TABLE  a
        ADD CONSTRAINT     a_namea_fk
        FOREIGN KEY  (namea)
        REFERENCES b (nameb)
    ;If you had a situation where you really needed to query a table in PL/SQL, and you weren't sure if the query would find anything, you could put the query in its own BEGIN ... EXCEPTION block, and test for NO_DATA_FOUND.
    If you're just checking to see if a row exists or not, you can always write a query that is guaranteed to return exactly 1 row, like this:
    BEGIN
        SELECT  COUNT (*)
        INTO    x
        FROM    b
        WHERE   nameb = :NEW.namea
        AND         ROWNUM  = 1;
        IF x = 0
        THEN  
            ...        -- print msgs, raise exceptions etc
        END IF;
    END;Edited by: Frank Kulash on Nov 14, 2012 9:22 AM
    Added example

  • How to create a foreign key for the table from two different tables?

    Hi All,
    I have a three table like below. In the below table SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK will be having the primary key for NAME column. The same SAMPLE_CONS3_CHECK table also having the primary key for NAME column and forieign key for SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK tables. See the below code 2
    code 1:
    CREATE TABLE SAMPLE_CONS_CHECK
            (NAME VARCHAR2(10),
            SERIES  VARCHAR2(5)
    CREATE TABLE SAMPLE_CONS2_CHECK
            (NAME  VARCHAR2(5),
             MODEL  NUMBER
    CREATE TABLE SAMPLE_CONS3_CHECK
            (NAME  VARCHAR2(5),
             MODEL_NO  NUMBER
            )code 2
    alter table SAMPLE_CONS_CHECK
    add constraint SAMPLE_CONS_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS2_CHECK
    add constraint SAMPLE_CONS2_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS3_CHECK
    add constraint SAMPLE_CONS3_CHECK_pk primary key (NAME)
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK1 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS_CHECK
        NAME
    ) ON DELETE CASCADE;
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK2 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS2_CHECK
        NAME
    ) ON DELETE CASCADE;From the above schenario i am able to insert the data to SAMPLE_CONS3_CHECK table. But the parent data is already available in the parent table. The problem is here two different constarints from two different tables. While inserting, it is checking from both the tables whether the parent is exist or not.
    How can i solve this problem? Can anyone halp me about this?
    Thanks
    Edited by: orasuriya on Aug 8, 2009 2:02 AM

    Actually the design is completely incorrect.
    What you say is
    I have
    'foo', 'foo series'
    'foo','foo model'
    'foo',666
    By virtue of table3 referring to both table1 and table2.
    This means you actually need to have 1 (one) table:
    'foo','foo series','foo model', 666
    And the 'problem' disappears.
    Sybrand Bakker
    Senior Oracle DBA

  • How can I create a new entry without using LOV for foreign keys.

    Referring to TUHRA sample application based on HR database schema. JDeveloper 10.1.3.0.4
    How can I create a new employee without using LOV for the foreign key "job_id".
    On the first page I would like to choose the job_title from adf read-only table.
    After clicking on the "create new employee button" a creation form appears in which the job_id field is set with previous selection.
    Regards M.Winkler
    Edited by: user3541283 on 06.10.2008 03:44
    Edited by: user3541283 on 06.10.2008 03:50

    Hi,
    usually the foreign key is only set if the VO you select is dependent from a master. If e.g. you have DepartmentsVO1 that has an EmployeeVO3 as its nested VO, then creating a new instance of employees automatically add the foreign key. If you add EmployeesVO1, which is not dependent to DepartmensVO1, then the foreign key is not set. So if this is the case in THURA (keep in mind that this is not an Oracle demo but a sample used in a book about ADF) then all you need is to take the independent VO when building the new employee form.
    Frank

  • How to create a Foreign key relationship between 2 user defined tables...

    Hi Folks,
    I have created two user defined tables... Where in i want to create foriegn key relationship between the 2 tables.... Can anyone guide the step by step procedure to do this scenario...
    Any help would be highly appreciated...
    Thanks

    Hi
    1.  In the 2nd table call the field of the 1st table which is a primary key.
    2.  Give the same field and dataelement name.
    3.  Select that field and then click on the foreign key field icon which is beside Search Help button.
    4. Then give short text, and the 1st table name.
    5. Then in the below box give the 2nd table name and 2nd table field name which you have called from 1st table.
    6. Then click on copy, then u will be able to see Check table name and check table field name beside foreign key table name.
    7. Then again click on copy.
    Regards
    Haritha.

  • Creating a foreign key constraint on a synonym of table in another schema.

    Hi,
    I am having two user operapps and oper
    owner of table po_vendors is operapps ,i have created a synonym in oper with select permission.
    now i am trying to create a foreign key.
    ALTER TABLE OPS_BR_VENDORS ADD ( FOREIGN KEY (VENDOR_ID) REFERENCES PO_VENDORS (VENDOR_ID));
    the bolded po_vendors is the synonym for the table po_vendors in operapps.
    i am getting the below error message.
    SQL> ALTER TABLE OPS_BR_VENDORS ADD ( FOREIGN KEY (VENDOR_ID) REFERENCES PO_VENDORS (VENDOR_ID));
    ALTER TABLE OPS_BR_VENDORS ADD ( FOREIGN KEY (VENDOR_ID) REFERENCES PO_VENDORS (VENDOR_ID))
    ERROR at line 1:
    ORA-01031: insufficient privileges.
    i have given dba privileges to oper user.
    Please advice.

    1) You cannot create a constraint on a synonym. You have to specify a physical table (i.e. OPERAPPS.PO_VENDORS)
    2) The owner of the OPS_BR_VENDORS table will need to have the REFERENCES permission on the PO_VENDORS table granted directly (not via a role).
    Justin

Maybe you are looking for

  • N8 / Belle / Car BT Audio - random problem with au...

    I updated my N8 to Belle when it was first released.  Ever since, I've been experiencing random problems with audio volume and how it is being output from the phone. I have paired my N8 with my car (2012 Subaru Legacy) which allows me to make phone c

  • Safari Not Loading (HELP!)

    I know this seems to be a common topic here, but I wanted to get my question in here as well! I have followed all of the suggestions that I have seen on this board and none of them have worked. I re-installed Safari using the custom install method, d

  • PS CS5 slowdown?

    I am using PS CS5 with WIndows Vista. CS3 works great, but when I upgraded to CS5, it regularly goes into slow motion like I have about 256M of memory. Actually I have 4G of RAM. I can close Photoshop and restart, and it will work fine for awhile. It

  • IBooks v1.2 upgrade or not?

    I wonder if I should upgrade to iBooks 1.2. In the user reviews I see a lot of people having trouble (missing books, all PDF's have same cover, ...) and some say not to upgrade. Should I skip this version, or does it work OK for most people?

  • Trouble Import Flash MX into Director MX

    Hi I am newbie. I had made a flash mx movie named main.swf. In this flash, i put a movieclip that loads a video named video.flv from a folder named Video. If i run my swf (with flash player), it works. I mean, the video is loaded. But the problem is,