Trigger - use one to create primary key values

I'm stuck on a simple use to do a TRIGGER that fires when you add new rows to a table and want to Developer SQL to add the primary key value.

I seem to be able to relax, but it is not inserted the primary key but giving a SQL error: ORA-00947: not enough values.

Here's what I have.

CREATE TABLE HF_fishers

(

contact_id INT NOT NULL

, name VARCHAR (25)

, last_name VARCHAR (35)

PRIMARY KEY (contact_id)

);

CREATE SEQUENCES HF_fishers_seq.

Then I ran the following trigger:

CREATE

HF_fishers_seq_trigger RELAXATION

BEFORE INSERTING

ON HF_fishers

FOR EACH LINE

BEGIN

IF (: new.contact_id IS NULL)

THEN

: NEW.contact_id: = NVL (: NEW.contact_id)

HF_fishers_seq. NEXTVAL

);

END IF;

END HF_fishers_seq_trigger;

=============

Then I executed the following SQL statement that gives the error.

INSERT INTO HF_fishers VALUES('Jacob','Muller');

But if I do everything is good except that it defeats the purpose of relaxation.

INSERT INTO HF_fishers VALUES(1,'Jacob','Muller');

MySQL has a nice 'AUTO_INCREMENT' command, but from what I understand in Oracle, I need to set up a trigger to automatically increment a column/cell, which in this case I use for the PRIMARY KEY.

3003916 wrote:

OK Jaramillo, I tried as you wrote, but what would be an INSERT statement correct?

-After the code trigger of Jaramillo

INSERT INTO HF_fishers (first_name, last_name) values ("Jesse", "Owens"); -I have the trigger but he made the mistake of duplicate key.

INSERT INTO HF_fishers values (hf_fishers_seq.nextval, 'Jesse', "Owens");  -No trigger but get key duplicated,.

INSERT INTO HF_fishers VALUES(:NEW_contact_id,'Jesse','Ownes'); -works without the trigger but the "get links" dialog box appears. So not much 'automatic' on this issue,.

My mistake.  Here is the modified version of the trigger. I removed the CONDITIONAL clause and comes to be a part of the body of the trigger.

So, I created the table, the sequence, the relaxation and ran the first two insert statements and it worked fine.  The third one you have invites SQL + or any tool you use to enter a value if she sees the ":" colon as a variable binding.  Colon only works in a trigger without asking for confirmation.

Here is the code and my exit I ran home

DROP TABLE hf_fishers CASCADE CONSTRAINTS PURGE;
DROP SEQUENCE hf_fishers_seq;

CREATE TABLE hf_fishers
(
contact_id   INTEGER NOT NULL
,first_name   VARCHAR(25)
,last_name    VARCHAR(35)
,PRIMARY KEY (contact_id)
);

CREATE SEQUENCE hf_fishers_seq;

CREATE OR REPLACE TRIGGER hf_fishers_seq_trigger
   BEFORE INSERT
   ON hf_fishers
   FOR EACH ROW
BEGIN

   IF(:NEW.contact_id IS NULL) THEN
      :NEW.contact_id := hf_fishers_seq.NEXTVAL;
   END IF;

END hf_fishers_seq_trigger;

INSERT INTO hf_fishers(first_name, last_name)
     VALUES ('Jesse', 'Owens');  -- Works with the trigger

INSERT INTO hf_fishers
     VALUES (hf_fishers_seq.nextval, 'Jesse', 'Owens');  --Works without using the trigger body code.

SELECT *
  FROM hf_fishers;

COMMIT;

The output

Deleted table.

Elapsed time: 00:00:00.05

Sequence has fallen.

Elapsed time: 00:00:00.02

Table created.

Elapsed time: 00:00:00.03

Order of creation.

Elapsed time: 00:00:00.02

Trigger created.

Elapsed time: 00:00:01.05

1 line of creation.

Elapsed time: 00:00:00.04

1 line of creation.

Elapsed time: 00:00:00.01

CONTACT_ID FIRST NAME LAST NAME

---------- ------------------------- -----------------------------------

1 Jesse Owens

2 Jesse Owens

2 selected lines.

Elapsed time: 00:00:00.04

Validation complete.

Elapsed time: 00:00:00.01

Tags: Database

Similar Questions

  • Shape of the apex - how to get the primary key value manually?

    Hello

    Whenever I create form by using wizard Apex, he asks me to specify the trigger/sequence/pl/sql function to fill the primary key value.

    However, if I want to specify primary key myself (ie. undetermined generated automatically), how I can clarify that?

    Thanx

    Hello

    You mean by yourself: by hand or by a pl/sql?

    If you say by trigger, the system does not take on what number is sent. If you can give it "manually".

    May I ask what is the reason for this?

    See you soon,.

    Arnaud

  • Another syntax for creating primary key


    Hello


    I have a question about the right way to create primary keys.
    Earlier, we were on Oracle 9i and we have upgraded to Oracle 10 g. The question is when creating primary key is allowed to create the unique index and then to create the primary key constraint? or directly create the first key is better? or are there ways to both the same?


    for example:
    one way:


    SQL & gt; CONN u2/u2@db1
    Connected.
    SQL & gt; create table a (a1, b1 varchar2 number (2), the date c1);


    Table created.


    SQL & gt; create an index on a (a1) tablespace unique pk_a t1;


    The index is created.



    SQL & gt; ALTER table a Add (constraint primary key (a1) using index pk_a);


    Modified table.
    Another way:
    SQL & gt; CONN u1/u1@db1
    Connected.
    SQL & gt; create table a (a1, b1 varchar2 number (2), the date c1)
    2.


    Table created.


    SQL & gt;
    SQL & gt; ALTER table a Add (constraint primary key (a1) using index tablespace t1 pk_a)
    2.


    Modified table.
    Which of the two approach is better? or are they the same?


    Thank you
    Cedric

    Oracle will attempt to create the index to apply the constraint. Of course, it is certainly possible that the creation of the index will fail, but you would be just to move the point of failure of the CREATE INDEX statement to the ALTER TABLE statement, assuming that everything else is equal (that is, you create the index in the same tablespace, quotas and tablespace sizes are the same, permissions are not changed, etc.)

    It may be preferable in some contexts to create a non-unique index before the creation of the constraint and instruct Oracle to use the non-unique index to apply the constraint. If you decide in the future to make the primary key constraint can be delayed, for example, have a non-unique index allows you to make this change without having to (implicitly), drop and re-create the index. A separate CREATE INDEX statement also influences when you go to remove a constraint / index. If the index was created before the constraint, you can remove the constraint without affecting the index. If the index was created after the constraint, deleting the constraint implicitly removes the index. Normally, particularly with OLTP applications, this doesn't buy you much. Sometimes, however, there are ETL process benefiting from such things.

    Justin

  • Form CHILD FRM-30100 error: block must have at least one element of primary key.

    Hi friends,

    I increased table DML child block of 1 to 10, but he gives me the error:

    FRM-30100: block must have at least one element of primary key.
    Block: CEC_ADJUSTMENT_RECON
    Form: CEC_ADJ
    FRM-30085: unable to adapt to the shape for the release.
    How does a form know that the table does not have primary key? Is it referring to it?
    
    
    Thanks a lot                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    You can not overcome this behavior, unless you click or to move to the next to the checkbox element.
    This is the default behavior.

    Make the property of block NVAIGATION STYLE as change recording so that when you press ENTER or TAB to the last point, the cursor automatically goes to the box.

  • Creating primary key based on the Date

    Hi all
    I am trying to create a unique ID for each record, based on the date that the record is created. Example, if the folder is created today, I want to the key is 20101130XX where XX is a sequential list of numbers e.g. 01, 02, 03 etc... in the case where more than one person creates a record today.

    If 3 people created record yesterday their unique ID would be

    2010112900
    2010112901
    2010112902

    and then comes the midnight and someone creates a new record, that it would be

    2010113000

    This is intended to give each record with a unique ID that will be used to reference the ticket.

    We are already using the date format, but currently users have to manually enter the id and who can create errors such as 2011112900 when it should have been 2010112900 then instead of 2010 they put 2011

    I'm not sure how to create a trigger to generate this type of unique identification number and would appreciate any help

    Thanks in advance

    Wally

    Never said it was perfect, but then again, it is a rather sticky issue... Reset sequence work would be scheduled to run @ some point... You entered in tables past 24/7? I would say that system could be locked for those 5 minutes sequence is updated, or the table is locked to allow no access while the process is...

    To be honest, that is the question in the design of a key value that is dependent on outside data, as apposed to a surrogate key, which is generated System... Again, you could have at ONCE and have the surrogate for a key key REAL primary and date + sequence as a secondary key for the use of basic unit of carbon...

    Thank you

    Tony Miller
    Webster, TX

    If vegetable oil is made from vegetables, then what is baby oil?

  • Copy a record ang get its new primary key value

    Hello again everyone!

    I need to copy a record from a table at the same table. Here is the sample table and data:

    CREATE TABLE (PRODUCTS)
    ID INTEGER NOT NULL,
    DESCRIPTION VARCHAR2 (80).
    PRICE NUMERIC (9,2),.
    KEY ("ID") PRIMARY CONSTRAINT 'PK_PRODUCTS '.
    );

    INSERT INTO PRODUCTS (DESCRIPTION, PRICE) VALUES (' PRODUCT 1', 8.5); -You will receive 1 trigger ID
    INSERT INTO PRODUCTS (DESCRIPTION, PRICE) VALUES (' PRODUCT 2', 7.0); -You will receive 2 ID by trigger

    Now, I need to copy data from product 1 on a new line on the table.

    I would use the following SQL statement:

    INSERT INTO PRODUCTS (DESCRIPTION, PRICE)
    SELECT DESCRIPTION, the PRICE OF PRODUCTS WHERE ID = 1 - assuming that I want to copy 'Product 1'
    RETURN ID IN: NEW_ID

    But as far as I know, this is not supported by Oracle. Is there no workaround solution to solve the problem?

    I can't use procedures, functions, or something like that. Must be a SQL statement.

    Once again, thank you all for help.

    Best regards

    user9936895 wrote:
    INSERT INTO PRODUCTS (DESCRIPTION, PRICE) VALUES (' PRODUCT 1', 8.5); -You will receive 1 trigger ID
    INSERT INTO PRODUCTS (DESCRIPTION, PRICE) VALUES (' PRODUCT 2', 7.0); -You will receive 2 ID by trigger

    I really, really, really hope that your trigger uses a sequence to generate pk

    I can't use procedures, functions, or something like that. Must be a SQL statement.

    If your trigger uses a sequence to generate the pk, I hope that there is a clause which no values if the KP value is zero...

    If Yes, then you could just do:

    INSERT INTO PRODUCTS (ID, DESCRIPTION, PRICE)
    SELECT id_sequence.nextval, DESCRIPTION, PRICE FROM PRODUCTS WHERE ID=1 --Assuming I want to copy "Product 1"
    
  • Difference between the immediate and normal constraint primary key value

    Hello
    I tried the following to understand the difference between immediate constraint set and the primary normal stress
    create table cust (cust_id number ,cust_name varchar2(25));
    
    alter table cust add constraint cust_id_pk primary key(cust_id)
    deferrable initially deferred;
    
    SQL> insert into cust values(1,'raj');
    
    1 row created.
    
    SQL> insert into cust values(1,'sam');
    
    1 row created.
    
    SQL> commit;
    commit
    *
    ERROR at line 1:
    ORA-02091: transaction rolled back
    ORA-00001: unique constraint (SCOTT.CUST_ID_PK) violated
    
    
    SQL> set constraint cust_id_pk immediate;
    
    Constraint set.
    
    SQL> 
    SQL> insert into cust values(1,'lata');
    
    1 row created.
    
    SQL> insert into cust values(1,'lata');
    insert into cust values(1,'lata')
    *
    ERROR at line 1:
    ORA-00001: unique constraint (SCOTT.CUST_ID_PK) violated
    The above error violation even works for a normal constraints primary / unique

    So what is the use of the command

    immediate Set constraint cust_id_pk;


    Thank you

    So what is the use of the command

    In fact, the use of the command when you're dealing with foreign key constraints. As explained below

     SQL>  create table cust (cust_id number ,cust_name varchar2(25), supplier_id number);
    
    Table created.
    
    SQL> create table supp(supplier_id number);
    
    Table created.
    
    SQL> alter table supp add primary key(supplier_id);
    
    Table altered.
    
    SQL>  ALTER TABLE cust ADD CONSTRAINT fk_cust_supp
      2    FOREIGN KEY (supplier_id)
      3    REFERENCES supp (supplier_id)
      4    DEFERRABLE
      5    INITIALLY deferred;
    
    Table altered.
    

    To insert a line in the cust table without entering Ref provider table supp

    SQL> insert into cust values(1,'raj',111);
    
    1 row created.
    

    Line by 1 created successfully (attention this validation is not yet done) because the foreign key constraint is initially deferred.

    Now

    SQL> set constraint fk_cust_supp immediate;
    set constraint fk_cust_supp immediate
    *
    ERROR at line 1:
    ORA-02291: integrity constraint (OWNER.FK_CUST_SUPP) violated - parent key not found
    

    Since Ref no outs in extra table so forced provider violated.

    allows to insert a row in the vendor corresponding with the vendor id in the cust table id

    SQL> insert into supp values(111);
    
    1 row created.
    

    Now, try

    SQL> set constraint fk_cust_supp immediate;
    
    Constraint set.
    

    but now, if you try to insert a row into the table cust without this vendor id in table supp, it give error (since now forced to check from the inserted row, even will not wait for commit)

    SQL>  insert into cust values(3,'bob',222);
     insert into cust values(3,'bob',222)
    *
    ERROR at line 1:
    ORA-02291: integrity constraint (OWNER.FK_CUST_SUPP) violated - parent key not found
    

    Also, in the case of primary key constraints will be checked when you perform VALIDATION, otherwise that it will allow you to insert the second row.

    SQL> alter table cust add constraint cust_id_pk primary key(cust_id)
      2  deferrable initially deferred;
    
    Table altered.
    
    SQL> insert into cust values(1,'raj');
    
    1 row created.
    
    SQL> insert into cust values(1,'sam');
    
    1 row created.
    
    SQL> insert into cust values(1,'bob');
    
    1 row created.
    
    SQL> commit;
    commit
    *
    ERROR at line 1:
    ORA-02091: transaction rolled back
    ORA-00001: unique constraint (OWNER.CUST_ID_PK) violated
    
    SQL> 
    
    SQL> drop table cust;
    
    Table dropped.
    
    SQL> create table cust (cust_id number ,cust_name varchar2(25));
    
    Table created.
    
    SQL> alter table cust add constraint cust_id_pk primary key(cust_id)
      2  deferrable initially deferred;
    
    Table altered.
    
    SQL> set constraint cust_id_pk immediate;
    
    Constraint set.
    
    SQL> insert into cust values(1,'raj');
    
    1 row created.
    
    SQL>  insert into cust values(1,'sam');
     insert into cust values(1,'sam')
    *
    ERROR at line 1:
    ORA-00001: unique constraint (OWNER.CUST_ID_PK) violated
    
    SQL> 
    

    Published by: Azhar Husain on July 27, 2011 12:01

  • Should I create primary keys or foreign first?

    I'm new to sql and a student please bear with me.

    I create a script so that when I run a sequence of tables are created. I created all of my fine tables but now I want to add the primary and foreign keys. I tried to do all this at once before but had problems, my idea was to use alter table instructions and add the constraints of key primary and foreign in this way.

    The thing I want to know is what to build first? Should I do any foreign keys and primary keys or visa versa? Or can I do them sequentially and connect relationships between the tables that I will. Thanks in advance!

    Hello

    One thing to remember as a student is to apply logic to the task at hand. In this case, to create a foreign key, it must refer to a primary key in its definition as well so the KP must exist first. What I tend to do is to break down as statements in separate files or sections separate scripts and execute it in a logical order. IE Tables first, and then of PK and UK followed by the FK etc.. I also prefer to create offline rather than constraints in create table statements.

    Hope this helps

    André

  • With custom auto-generated primary key value

    How to implement the the custom generated automatically Coordinated as 'ISSUE00001', 'ISSUE00002' ADF entity object.

    Hello
    your PK should be varchar2 if you use oracle DB or what?
    While you use to generate the PK value you expect, you can use the database for him.
    http://www.exploreoracle.com/2010/10/11/sequence-number-for-primary-key-in-Oracle-ADF-JDeveloper/
    in this site, call your function in the dodml method. without using the sequence.
    If (operation == DML_INSERT) {}
    inside to call your function that allows to generate number with the string value. (u concat/join 'FROM' value for your build number max)

    }

    Thks.

  • Create primary key also Select

    In Oracle, how we specify a primary key in a creation like the select statement? I ran a simple statement, but received the error ORA-00933. What I have to do two steps with created first table and alter the table to add the key?

    Thank you



    CREATE TABLE Test as
    SELECT
    *
    SOURCE one
    WHERE a.sys = 100
    PK1 CONSTRAINT PRIMARY KEY (account ID)
    SQL>  create table t (a primary key) as select 1 from dual
    /
    Table created.
    
  • Using XML as a pair key / value in OSB 11 g

    Hi all

    I made a new Test project. There are only 2 files:
    1 proxies - that contain proxy services
    2 xml - containing XMLs

    An example of XML (XML name - TestXML) present in the xml file:

    < valueDetails >
    ABC < key1 > < / key1 >
    < > 123 key2 < / key2 >
    a12s < key3 > < / key3 >
    < / valueDetails >

    I want to use in the pipeline of proxy as key-value property services. How do I get there?

    I use OSB 11 GR 1 material.

    Thanks in advance!

    Kind regards
    Karthik.

    Save the XML as a resource of xquery to the osb. Then, use an entitled action for load in the pipeline. For example affect XQuery resources KeyPairsXML to $keypairs. After this $keypairs will be your xml and appropriate xpath allows to recover the key you want,

  • Creating primary key in online?

    My database is oracle11g. My environment is 24 * 7.

    I know that we can create indexes online. But here it is the primary key. I do below things... These tasks must not lock the table.

    1 remove the primary key
    2. recreate the primary key
    3 remove the normal index
    4 re-create the normal index.

    Task 4 can be done online. I'm afraid the rest of the task.

    1. no oracle locks the table while dropping the PK?
    2. how to recreate the PK online?
    3 oracle locks the table while removing the index?

    Please let me know.

    Dear Shrinika,

    If you read the ticket of Richard, you will find the answer to your question.

    There is an improvement over 11 g and concurrent transactions are not owned by a lock of index.

    Index lock will wait only active transaction that was created before the create index command.

    Ogan

  • How to create an entity with more than one primary key.

    Hello

    JDeveloper Version 11.1.2.4.0

    I am trying to create an entity object based on a table with 5 columns. The combination of them is unique.

    I do the five columns of primary keys, but when I delete a line I: RowAlreadyDeletedException, although always the line exists in the database.

    Also displaying the view sometimes I get Houston-25019: line entity oracle.jbo.Key [1 key 2 null null NULL].



    How to create an entity based on one object several columns in the primary key?

    I don't want to add an additional column to a primary key, because this table is used in many PL/SQL procedures, and I'm not sure that this will not affect the.

    Also using Rowid as a primary key should be avoided.

    Kind regards

    Pamela.

    As I said, the framework is not like that

    Check this old (but still relevant) blog of Sung Im on Table Whose Primary Key entity object can be NULL

    describing the reason behind the behavior you're seeing and the way around.

    Or you use the secondary key rather as described here Wael Abdeen Blog, how to look at the views - part 2 | Oracle ADF as a secondary key composed of more then one column can have null values.

    Timo

  • How to extract the values of the line full in the bean to support using the primary key

    Hello

    I have a table that has columns as plant_name, business planner email id and identification of email resident engineer. Here, Plant_name is the primary key.

    Now, I have this plant's name slipped and dropped like selectonechoice (drop) on page jsff. In this user can select any name of 1 plant drop down.

    Right now, I can go get plant in backing bean name, but I can't understand how business plan for extraction and identification of email of the engineer resident in this key primary-plant_name at the bean to support.

    Please let me know if anyone has an idea in this regard.

    JDeveloper version 11.1.1.6.0

    Thanks in advance.

    Sneha

    Sneha211 wrote:

    On the jsff page

    required = "#{bindings." Plant.hints.Mandatory}.

    shortDesc = "#{bindings." Plant.hints.ToolTip}.

    ID = "soc1" unselectedLabel = "- Select -"

    autoSubmit = 'true '.

    Binding = "#{backingBeanScope.backingbean.plantbean}" > "

    ID = "si1" / >

    In backing bean

    DCBindingContainer = lBindingContainer

    (DCBindingContainer) BindingContext.getCurrent () .getCurrentBindingsEntry ();

    DCIteratorBinding lBinding = lBindingContainer.findIteratorBinding("SupplierVO1Iterator");

    NewRow row = lBinding.getCurrentRow ();

    String aamplant1 = (String) newRow.getAttribute ("Plant");

    Hi Sneha, you've written code for it

    you have found the current line and the primary key then this line, then why you not not using this same rank to get the other attributes?

    NewRow row = lBinding.getCurrentRow ();

    String aamplant1 = (String) newRow.getAttribute ("Plant");

    String businessPalnner = (String) newRow.getAttribute ("business_planner"); Returns the value of the same line

    Engineer in String = (String) newRow.getAttribute ("engineer");


    OR if your condition is like that-

    you have a primary key field value, but you do not have the corresponding line, then you can get that line and it's attribute by using the primary key value

    See - http://adfgouravtkiet.blogspot.in/2012/10/filtering-of-data-from-vo.html

    Hope it helps

    -Ashish

  • Make required error appears only the primary key generated in prior Database Table insert trigger

    Dear all,

    I am a beginner in the ADF and am under Jdeveloper Studio Edition Version 12.2.1.0.0.


    I'm trying to insert a record, I created the trigger for insertion prior to get the primary key and set some other default values.


    On the page, I did read-only primary key column and false required.


    When I try to save - commit (Programmatic), I get errors for the required value. How can I stop this errors.


    Secondly, I also tried changing the agent to disabled on the attribute View object that raised the error below:


    < oracle.dfw.impl.incident.DiagnosticsDataExtractorImpl > < DiagnosticsDataExtractorImpl > < createADRIncident > < incident created 148 to key problem "DFW-99998 [oracle.jbo.PersistenceException] [oracle.jbo.server.RowReference.verifyPrimaryKeys] [Proposals]" >


    Hoping for help.


    Thanks and greetings


    Arif Khadas

    If the primary key values from DB sequence, you can follow this approach:

    Using the sequence of database in ADF - Souza Waslley Blog

    Oracle Fusion Middleware Technologies: ADF 11 G: generate the primary key sequence number

    Otherwise, instead of DB trigger, create the DB function that retrieves the value of the PK and call stored function in the overloaded method create() entity:

Maybe you are looking for