Triggers to insert primary key

I have two tables in database namely CM_BOM and CM_BOM_ITEM. The table columns are as follows :
In CM_BOM table
CR_ID
CR_BOM_CODE
CR_BOM_NAME
CR_FG_CODE
CR_ID is primary key
Trigger to insert primary key data is as follows :
CREATE OR REPLACE TRIGGER COSTMAN."CM_BOM_T1"
BEFORE INSERT ON "CM_BOM"
FOR EACH ROW
DECLARE
L_ID NUMBER;
BEGIN
IF :NEW.CR_ID IS NULL THEN
:NEW.CR_ID := CM_RECIPE_SEQ.NEXTVAL; --L_ID;
END IF;
END;
In CM_BOM_ITEM table
CR_ID
CR_ITEM_ID
CR_FG_CODE
CR_RM_CODE
CR_RM_QTY
CM_ITEM_ID is primary key. Trigger to insert primary key data is as follows :
CREATE OR REPLACE TRIGGER COSTMAN."CM_BOM_ITEM_T1"
BEFORE INSERT ON "CM_BOM_ITEM"
FOR EACH ROW
DECLARE
L_ID NUMBER;
BEGIN
IF :NEW.CRI_ITEM_ID IS NULL THEN
:NEW.CRI_ITEM_ID := CM_RECIPE_SEQ.NEXTVAL;
END IF;
END;
Now, i want to the CR_ID in table CM_BOM_ITEM to get automatically inserted while adding any rows in the table.
How could i do this ? Please suggest ?
Yogesh

In your code where you perform the insert into the parent table, you can use the RETURNING clause to receive the primary key value that the trigger on the parent table has assigned to the parent-row that was just inserted.
  insert into parent_table(....) values(....)
  returning CR_ID into some_local_variable;Then use this value when you insert the foreign key row subsequently.

Similar Messages

  • Difference in Triggers for populating Primary Keys

    version: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    Hello,
    I have a question regarding using Triggers to populate Primary Keys.
    One Trigger I've seen written like this:
    CREATE OR REPLACE TRIGGER "BI_MY_TABLE"
        BEFORE INSERT
        ON my_table
        FOR EACH ROW
    BEGIN
        IF :new."MY_TABLE_ID" IS NULL THEN
            SELECT "MY_TABLE_SEQ".NEXTVAL INTO :new."MY_TABLE_ID" FROM DUAL;
        END IF;
    END;
    And another Trigger written like this:
    CREATE OR REPLACE TRIGGER "BI_MY_TABLE"
        BEFORE INSERT
        ON my_table
        FOR EACH ROW
    BEGIN
       FOR c1 IN (SELECT my_table_seq.NEXTVAL next_val FROM dual)
       LOOP
          :new.my_table_id := c1.next_val;
       END LOOP;
    END;
    The first version is using an IF statement and the second version is using a LOOP.
    My questions are:
    Is there really any difference in the technique used to create the Trigger?
    Is there any "benefit" in using one technique over the other?
    Is there a more preferred method/technique to populating Primary Key columns?
    Thanks,
    Joe

    Hi, Joe,
    The second way (using a loop) is just silly.  Don't use a loop.
    Starting in Oracle 11, you don't need to use dual at all; you can do it like this:
    CREATE OR REPLACE TRIGGER BI_MY_TABLE 
        BEFORE INSERT 
        ON my_table  
        FOR EACH ROW  
    BEGIN 
        IF  :new.MY_TABLE_ID  IS NULL  THEN 
            :new.MY_TABLE_ID  := MY_TABLE_SEQ.NEXTVAL;  
        END IF;  
    END  BI_MY_TABLE; 

  • How to build a tabular form with a by the user insertable primary key

    I have build a build a tabular form with the wizzard. Wat should I do to make the primary key insertable by the user.
    When I change the PK from 'hidden' to 'text field', I get a checksum error when i am trying to insert.

    Fred: When you use the tabular form wizard, notice the help text on the right hand side of each page. The help page where you define the type of primary key (Existing trigger, PL/SQL function, existing sequence) clearly states
    Tabular forms do not support user entered primary key values
    Makes sense when you think about it. The MRU process needs to determine whether to update a record or insert a new record. It does that by comparing the checksums (and/or) pk values from when the page was first rendered and then when you make changes and submit it. Newly inserted rows will have a blank PK/checksum.
    If you allow user to change the PK, how will the system know which rows are new and which ones are old?
    For example, lets say you have
    create table t
    pk int primary key,
    data varchar2(10)
    )You have 2 rows
    1 red
    2 yellow
    If the PK were to be editable, user could go in and change the above to
    2 red
    1 yellow
    Now what? Would you like the system to create a new row with 1/yellow or change the existing pk=1 row to yellow? Same with the other row.
    Bottom line: The built-in processes dont support this. You can always write your own manual tabular form and implement whatever you logic you wish in your After Submit processes.
    Hope this helps.

  • Solved: ADF BC and primary keys - how to implement without using triggers

    Using the following OBE as an example:
    http://www.oracle.com/technology/obe/obe9051jdev/ADFWorkshop/BuildingADFApplicationsWorkshop.htm
    There is just one view that has CustomerId defined as a primary key, where the value for the primary key comes from the customer_seq sequence.
    How do you create the model using ADF BC entity to create an entity object that has a primary key that needs to be populated by a sequence table when inserted WITHOUT using a trigger?
    Basically I want to just use ADF BC instead of toplink in the OBE. We do not use triggers to insert primary keys, so this example is a good match for what I need.
    Can someone help me out. How do I adjust the model to use just ADF BC - how do I define the entity object to use a sequence. Do I just override the create method in the impl? Is it that simple? Or is there a way to do this point and click in the entity tool.
    Thanks!

    I'm not the dba (or one of several) - so don't shoot the messenger... the dba's do not like to use triggers in the code. I have been told that this has caused too many problems in application development.
    I don't ask why, just deal with the fallout.
    I did try using the following code in a create method:
    protected void create(AttributeList attributeList)
    super.create(attributeList);
    SequenceImpl s = new SequenceImpl("customers_seq", getDBTransaction());
    // this.setCustId(s.getSequenceNumber());
    this.createPrimaryKey(s.getSequenceNumber());
    When I run the test program for the module, I get a new entry with the id empty and greyed out. I was hoping that this would be filled in on the actual insert, but no joy. As soon as I try to commit, I get an error:
    (oracle.jbo.AttrValException) JBO-27014: Attribute CustId in CustomersWSView is required)
    So what needs to be done?
    Message was edited by:
    klee

  • Parameters in Url..how do I use login information to insert the primary key

    Uggg, it is 3 am, I am so tired. Please help.
    I have made a registration page for my site. Hurray it works.
    Login Page. It works
    Protected some pages. Works
    Now I am trying to make a page that the users can go to and update their user information. User name, password, email ect.
    I can get it to prepopulate if I put ?id=3, or someother primary key in the url by hand.....and it does update the data.... but I can't, for the life of me, figure out how to make it use the users login information to get and insert the primary key in the url from the link to the update page.
    I have used the hyperlink box and chose the updateaccount.php file, then went to parameters and selected Name: id Value: I chose id from the dropdown from the data base. This puts in an echo that looks like it should work. NO SUCH LUCK.
    Pleeeese!!! What am I doing wrong.
    I am a total novice. Done a few static sites. So please speak slowly.
    Thanks sooooo much

    I really can´t recommend exposing critical stuff like e.g. the user´s login_id in the URL, because once it´s visible, it can be changed by anyone. Better insert the Session Variable kt_login_id, which will only be availabe on a custom PHP page when inserting...
    <?php session_start(); ?>
    ...on line 1 of this document.
    Cheers,
    Günter

  • How do I autogen a value for primary key on inserts

    I'm running 4.0. I am writing an app that maintains distributed database inventory information. All of my tables have surrogate numeric primary keys. I have created several report/form combinations. From the report, I can choose to create a new instance of an object; Server for instance. When I click the "Add Server >" button, the Detail page opens for me to create the new entry. On this page, I need to have the Server_ID autogenerated. I'm thinking something as simple as "Select (max(server_id)+1) from Server" should do. In fact, it looks like it is going to work because the field gets populated correctly. But, when I click the "Create" button on this page I get an error that says the Server_ID is null. Seems like the generated value isn't making it to the INSERT statement.
    On the Page Definition, I have Server_ID set as Display Only and in the Source section for the attribute I have "Only when current value in session state is null" selected and "SQL Query (return single value)" selected with "Select (max(server_id)+1) from Server" in the "Source value or expresssion" field.

    Hi Ken,
    From your description it appears you want the new server ID to be assigned and show on the page prior to collecting the rest of the information, rather than assigning it upon saving the new row. What you're doing will get the next available ID, but what happens if two or more people are entering new servers at once? There's a good chance they'll all get the same next ID.
    Tony's suggestion will ensure the uniqueness of the server ID because it'll get assigned upon saving the row, rather than on display of the page where a user could leave the screen sitting there while others "take" that next ID. You can return the value that the trigger assigns for display - if you're using an Automatic Row Processing process, see the Return Key into Item setting.
    If you're going to stick with your approach and just need to know how to make sure that field is included in the INSERT, you need to create a computation on that item and move your "select max..." there, and then for the server ID item change the Source Used to "Always...", Source Type to Database Column, and specify the column name from the table in the Source Value. The reason is hasn't been working is that field isn't currently mapped to the table column.
    Hope this helps,
    John

  • Primary Key rule Violation error while Insert Record in Compact DB

    Hi All,
    I have One Table in Server Name "Student"  when i Synchronize this with the help of Microsoft Synchronization Framework
    same Table schema with Data has been create in CompactDataBase.
    When i insert data in CompactDataDase it give me Primary Key Violation error.
    Please Suggest
    Example
    Table Structure is as Follows:-
    Create Table Student(
    [Emp_id] int IDENTITY(1,1) NotNull,[Emp_Name] int NOTNULL );insert into Student Values('John');insert into Student Values('Joe');Thanks & RegardsNamit Jain

    try this and see if it solves,
    also, Emp_name data type is int. it should be varchar.
    I suspect the reason is because you already have some data in student table but you identity seeds were not updated and hence it is trying to insert a row with emp_id value that already exists.and hence the primary key violation. also, your table DDL did
    not really have an primary key but it would still error since you are inserting duplicate row in the identity column.
    so, try resetting the identity seed value to the max(emp_id) in the table.
    select max(Emp_ID) from  student
    --use the output of the above statement
    DBCC CHECKIDENT ('Student', RESEED,<<--use the output of the above statement-->>)
    --your max(emp_id) should match with last_value column in the below( do not if this query would run in compact DB though)
    select seed_value,increment_value,last_value from sys.identity_columns where object_id=object_id('Student')
    now, try your insert.
    Hope it Helps!!

  • Primary Keys and Triggers

    I am developing a web application for the agency I work for and would like to use toplink (10g, aka 9.0.4). The agency has hade a policy since about Oracle 6 that all primary keys will be generated by a standard trigger returning a 32 character string. This policy is unlikely to change.
    Can toplink be used in this scenario? It does not appear that this is possible. I have seen the "return policy" example which appears to be a solution, but this is for a prototype version of 10g that is not yet released. At least, that is my interpretation.
    Can toplink 10g (9.0.4) insert records into tables where the primary key is generated by a trigger?
    Can this be configured in the Workbench or is this configured manually (if at all)?
    Thanks,
    Brad Smith

    Really it's an impedence mismatch issue.
    With or without TopLink, no matter what you do you're going to always have to do two round trips to get new data in the database (once to Insert it and once to read the PK for use in the cache).
    The question I usually ask is -- is this generated PK relevant to your business model? If it's not relevant, then don't map it, and create and use your own PK that can be managed in the mid-tier, use native sequencing, or some other O-R friendly approach. Go ahead and let the database trigger-generate keys, as long as you have some other unique value for the object, then it doesn't matter if the DB trigger generates one for it's own purposes.
    If you do at some point need this tigger generated value, you can make use of events. Pre/post insert/update/delete/write, whatever, events can be used to get/manage the trigger generated data on the database through JDBC calls.
    Bottom line is that impedence mis-match is your enemy in this situation, and TopLink has the event framework at your disposal to work with this mismatch.
    - Don

  • Recreate indexes,triggers and primary keys.

    Hi All,
    We have done an import of few table from MS SQL Server to oracle. But we couldnt see the indexes, triggers, primary key, foreign key of those tables.
    Could you please let us know how to recreate the primary key, foreign key, indexes, triggers etc of those tables.
    Pl suggest.
    Thanks in advance!
    Regards,
    Vidhya

    >
    We have done an import of few table from MS SQL Server to oracle
    >
    What does that mean exactly? How did you do an import from sql server to Oracle?
    Post your 4 digit Oracle version (result of SELECT * FROM V$VERSION) and the exact steps you took to 'import'.

  • Task-flow for inserting a record in a popup: error on primary key.

    Hi all,
    I am using Jdeveloper 11.1.1.2.
    I am trying to display a bounded task flow in a popup launched from a page. I am following the steps in: http://www.oracle.com/technology/products/jdev/tips/fnimphius/popupinuishell/declarative_popup_in_uishell.html
    I have a view object (myVO) and I have a page (page1), where I can edit the records of myVO. In this page I have a button that launches (in a window) a task-flow (insertTF, that uses existing transaction if possible, composed by page2 and page3) where I can insert a new record in two step (using a train).
    At the end of the train I can save or cancel (task flow return activity) the inserting record.
    The button cancel work well, but the button save does not. When I click on it, I return in page1 but I have this error: Error: another user modified row with primary key oracle.jbo.Key [[+numberOfKey+]].
    If I see the database navigator or I refresh the page, I can see the record just inserted.
    How can I do to remove this error?
    Thank you
    Andrea
    Edited by: Andrea9 on 10-dic-2009 06:39

    There are default values coming from the DB. There are also default values that I have setted in myModel on myEO.
    I am the only user manages the database, there are no other users.
    So, how can I solve this problem? Have I to remove the default value on inserting? From DB or from myEO?
    thanks in advance
    Andrea

  • Insert values of form on a table with compound primary keys in APEX

    Good evening,
    I have a table with compoud primay keys. On ER model I had a many to many relation and when I coverted to relational model I've got a table with the primary keys of the two entities.
    My problem now is that I am trying to build an APEX application with a Form/Report and I want to insert a tuple both on the "entity" and on the table with two primary keys.
    I created a trigger with
    CREATE OR REPLACE TRIGGER ins_key_elem
    INSTEAD OF INSERT
    ON v_key_elem
    REFERENCING NEW AS NEW
    FOR EACH ROW
    BEGIN
    INSERT INTO elem_type (elem_key, type_key)
    VALUES (:NEW.elem_key, :NEW.type_key);
    INSERT INTO elem(elem_key, name)
    VALUES (:NEW.elem_key, :NEW.name);
    END;
    Is that ok? If it is, now how I can use that trigger to do what I need? i.e. insert the tuple on the two tables when I use the create button of the form
    Edited by: 934530 on May 15, 2012 2:36 PM

    Nevermind...figured it out. Was able to set the value on the Report Attributes page.

  • Primary Key in INSERTs

    Hi!! :-)
    Im currently trying to access some Postgres-database from an Enterprise-App running inside Sun App Server 9... Some of th tables have a primary-key-field with type SERIAL, so Postgres creates the value for those fields!!
    Now: How can i achieve, that the app-server does not try to write into those fields??
    Specifying insertable=false is ignored and when i specify insertable=false and updatable=false i get the following error on deployment:
    Deploying application in domain failed; Exception [TOPLINK-0] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.IntegrityException Descriptor Exceptions: --------------------------------------------------------- Exception [TOPLINK-46] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.DescriptorException Exception Description: There should be one non-read-only mapping defined for the primary key field [dsl_payments.id]. Descriptor: RelationalDescriptor(de.meitnerweg.netzag.dsl.persistence.DslPayment --> [DatabaseTable(dsl_payments)]) Runtime Exceptions: --------------------------------------------------------- Exception [TOPLINK-0] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.IntegrityException Descriptor Exceptions: --------------------------------------------------------- Exception [TOPLINK-46] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.DescriptorException Exception Description: There should be one non-read-only mapping defined for the primary key field [dsl_payments.id]. Descriptor: RelationalDescriptor(de.meitnerweg.netzag.dsl.persistence.DslPayment --> [DatabaseTable(dsl_payments)]) Runtime Exceptions: ---------------------------------------------------------
    Anyone ideas??
    :-)

    The blog here describes how to work with this situation.
    http://blogs.sun.com/Glassfish_PostgreSQL/entry/introducing_support_for_postgresql_in
    Look into known Issues / Workaround sections.

  • Issue with INSERT INTO, throws primary key violation error even if the target table is empty

    Hi,
    I am running a simple
    INSERT INTO Table 1 (column 1, column 2, ....., column n)
    SELECT column 1, column 2, ....., column n FROM Table 2
    Table 1 and Table 2 have same definition(schema).
    Table 1 is empty and Table 2 has all the data. Column 1 is primary key and there is NO identity column.
    This statement still throws Primary key violation error. Am clueless about this? 
    How can this happen when the target table is totally empty? 
    Chintu

    Nope thats not true
    Either you're not inserting to the right table or in the background some other trigger code is getting fired which is inserting into some table which causes a PK violation. 
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Problem with inserting into table that has autogenerated primary key

    hi
    i am working on EJB3.
    i am trying to insert object into table.Primary key of table will be generated automatically.I tried following statement for insertion,
    em.persistent(customerObj);
    but it throw following exception,
    javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): customer.CustomerInfo
         at org.jboss.ejb3.tx.Ejb3TxPolicy.handleExceptionInOurTx(Ejb3TxPolicy.java:69)
         at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:83)
         at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:191)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:76)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:62)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:77)
         at org.jboss.ejb3.security.Ejb3AuthenticationInterceptor.invoke(Ejb3AuthenticationInterceptor.java:102)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:47)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:211)
         at org.jboss.ejb3.stateless.Stateles
    can anyone tell me is there any other way to acheive the same.
    i thought of doing using insert query,but i am not sure about the syntax to be used.
    could anyone help me ?
    thanks in advance...

    That's why you should use PreparedStatement instead of Statement. Its setString() method will escape that value for you properly when you bind it.
    %

  • How do you insert new records into multiple tables using the same unique primary key?

    I’ve created a PHP site and MySQL server using a free app called XAMPP.  I have successfully created a form in Dreamweaver that will write data to a (name) table in the SQL database.  Here’s my question: How do you write to two (or more) tables in the same database and pass the same primary key to both tables?  In the SQL database, I defined the first field as ID and set it as the primary key with auto update.  So, when you insert a new record, it creates a unique primary key for that record.  In my form, I’m capturing info that needs to be stored to two tables at the same time; a Name table and Address table. Since the Name and Address tables use the ID field as the primary key, I believe I will need to pass the ID value from the Name table to the insert of the Address table to insure they both have the same primary key, right?

    No. You probably need the primary key from one table to be a foreign key in the other tables. In any case, I believe you can use two methods to obtain the auto generated key. First with SQL:
    http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
    And the other using a PHP function:
    http://us3.php.net/mysql_insert_id

Maybe you are looking for

  • So i have an iphone4 but i have sprint, is there a way i could just use it as an itouch ?

    i dont even have a sim card for it is there a way i could get a sim card just so i can use the phone and its apps like an itouch ???

  • Items given for free

    Hi, I need a list of the most commonly used scenarios where an item is given away free. And then  a detailed listing of the pros and cons... plus what happens to the accounting document... the invoice and other things?

  • Web Dynpro ABAP application

    Hi All, Is it possible to make a Web Dynpro application available on internet without using Portal? How? Thanks Hardik

  • IPhone 5s stuck on "connect to iTunes" after trying to update to iOS8

    When I was connecting my iPhone 5s to my computer to update it to iOS 8 it started working perfectly fine but then it said looking for iPhone and then it wouldn't find it and it told me error and now my iPhone is stuck on connect to iTunes even thoug

  • Rango de valores numéricos ?

    Hola buenas, estoy utilizando una versión de prueba de FormsCentral (Acrobat XI Pro) y a la hora de intentar definir rango de valores en un cuadro de texto con formato numérico no veo opción alguna, así como tampoco para configurar el número de decim