Sequence values

I have a sequence whose max value with the help of a trigger is inserted in a table column. I've noticed that sometimes the consecutive values of the sequence differ not by one but by variable number.
I have Increment by 1 and Cache 20 in the sequence.
It's not making me major problems, but I's wondering whats the deal?
thanks

Hello,
Take a look at the following AskTom thread which explains what you're seeing -
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:530735152441
In short, nothing to worry about, the way they're working is to maximise scalability.
BTW, if your application has frequent simultaneous updates to that table, then you will benefit from creating the sequence with a larger cache (rather than just 20).
Hope this helps,
John.
http://jes.blogs.shellprompt.net
http://apex-evangelists.com

Similar Messages

  • Unable to save Sequence value to Database

    Hi,
    I am trying to pupulate a sequence value so that I can use it as primary key along with the combination of other columns later. My problem is that the sequence value is getting populated on the page with the right value, But is not getting saved to the database. The Column is there in the VO. The column is blank on the table. When I print it(System.out.println("Seq=" + xSeq.getText(pageContext));), the value is null. Can anyone please advice what I am doing wrong OR if I am missing anything here.
    Thanks
    Ali
    My CO file:
    ============
    package lac.oracle.apps.lac.jobperf.server.webui;
    import oracle.apps.fnd.common.VersionInfo;
    import oracle.apps.fnd.framework.webui.OAControllerImpl;
    import oracle.apps.fnd.framework.webui.OAPageContext;
    import oracle.apps.fnd.framework.webui.beans.OAWebBean;
    import oracle.apps.fnd.framework.OAApplicationModule;
    import oracle.apps.fnd.framework.webui.OADialogPage;
    import oracle.apps.fnd.framework.webui.TransactionUnitHelper;
    import oracle.jbo.domain.Number;
    import oracle.apps.fnd.common.MessageToken;
    import oracle.apps.fnd.framework.OAApplicationModule;
    import oracle.apps.fnd.framework.OAException;
    import oracle.apps.fnd.framework.OAViewObject;
    import oracle.apps.fnd.framework.webui.OAWebBeanConstants;
    import oracle.apps.fnd.framework.webui.beans.layout.OAMessageComponentLayoutBean;
    import oracle.apps.fnd.framework.webui.beans.layout.OAPageLayoutBean;
    import oracle.apps.fnd.framework.webui.beans.message.OAMessageStyledTextBean;
    import com.sun.java.util.collections.HashMap;
    import oracle.bali.share.util.IntegerUtils;
    import oracle.apps.fnd.framework.server.OADBTransaction;
    * Controller for ...
    public class ReviewCreateCO extends OAControllerImpl
    public static final String RCS_ID="$Header$";
    public static final boolean RCS_ID_RECORDED =
    VersionInfo.recordClassVersion(RCS_ID, "%packagename%");
    * Layout and page setup logic for a region.
    * @param pageContext the current OA page context
    * @param webBean the web bean corresponding to the region
    OAApplicationModule am; // dave
    OADBTransaction oadbxn; // dave
    oracle.jbo.domain.Number Seq;
    public void processRequest(OAPageContext pageContext, OAWebBean webBean)
    // Always call this first
    super.processRequest(pageContext, webBean);
    am = pageContext.getApplicationModule(webBean); // dave
    oadbxn = am.getOADBTransaction(); // dave
    OAPageLayoutBean pageLayout = pageContext.getPageLayoutBean();
    OAMessageComponentLayoutBean mainRn = (OAMessageComponentLayoutBean)pageLayout.findIndexedChildRecursive("MainRN");
    // If isBackNavigationFired = false, we are here after a valid navigation
    // (the user selected the Create Review button) and we should proceed
    // normally and initialize a new Review.
    if (!pageContext.isBackNavigationFired(false))
    // We indicate that we are starting the create transaction(this
    // is used to ensure correct Back button behavior).
    TransactionUnitHelper.startTransactionUnit(pageContext,"jobperfCreateTxn");
    // This test ensures that we don't try to create a new review if we
    // had a JVM failover, or if a recycled application module is activated
    // after passivation. If this things happen, BC4J will be able to find
    // the row you created so the user can resume work.
    if (!pageContext.isFormSubmission())
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    // String Seq = (String)oadbxn.getValue("Seq");
    oracle.jbo.domain.Number Seq = oadbxn.getSequenceValue("lac.LAC_CM_PERF_REVIEW_SEQ");
    OAMessageStyledTextBean xSeq = (OAMessageStyledTextBean)mainRn.findIndexedChildRecursive("Seq");
    xSeq.setText(Seq.toString());
    am.invokeMethod("createReview",null);
    // Initialize the ApplicationpropertiesVO for PPR.
    // am.invokeMethod("init");
    else
    if (!TransactionUnitHelper.isTransactionUnitInProgress(pageContext,"jobperfCreateTxn", true))
    // We got here through some use of the browser "Back" button, so we
    // want to display a stale data error and disallow access to the page.
    // if this were a real application, we would propably display a more
    // context-specific message telling the user she can't use the browser
    //"Back" button and the "Create" page. Instead, we wanted to illustrate
    // how to display the Applications standard NAVIGATION ERROR message.
    OADialogPage dialogPage = new OADialogPage(NAVIGATION_ERROR);
    pageContext.redirectToDialogPage(dialogPage);
    } // end processRequest()
    * Procedure to handle form submissions for form elements in
    * a region.
    * @param pageContext the current OA page context
    * @param webBean the web bean corresponding to the region
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
    {    //super.processFormRequest(pageContext, webBean);
    // Always call this first.
    super.processFormRequest(pageContext, webBean);
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    OAPageLayoutBean pageLayout = pageContext.getPageLayoutBean();
    OAMessageComponentLayoutBean mainRn = (OAMessageComponentLayoutBean)pageLayout.findIndexedChildRecursive("MainRN");
    // Pressing the "Apply" button means the transaction should be validated
    // and committed.
    // OAPageLayoutBean pageLayout = pageContext.getPageLayoutBean();
    // String Seq = SeqText.getText(pageContext);
    oadbxn.putValue("Seq", Seq);
    am = pageContext.getApplicationModule(webBean);
    oadbxn = am.getOADBTransaction();
    if (pageContext.getParameter("Apply") != null)
    // Generally in the tutorial application and the labs, we've illustrated
    // all BC4J interaction on the server (except for the AMs, of course). Here,
    // we're dealing with the VO directly so the comments about the reasons
    // why we're obtaining values from the VO and not the request make sense
    // in context.
    OAViewObject vo = (OAViewObject)am.findViewObject("jobperfVO1");
    // Note that we have to get this value from the VO because the EO will
    // assemble it during its validation cycle.
    // For performance reasons, we should generally be calling getEmployeeName()
    // on the EmployeeFullVORowImpl object, but we don't want to do this
    // on the client so we're illustrating the interface-appropriate call. If
    // we implemented this code in the AM where it belongs, we would use the
    // other approach.
    String employeeName = (String)vo.getCurrentRow().getAttribute("FullName");
    // We need to get a String so we can pass it to the MessageToken array below. Note
    // that we are getting this value from the VO (we could also get it from.
    // the Bean as shown in the Drilldwon to Details lab) because the item style is messageStyledText,
    // so the value isn't put on the request like a messaqeTextInput value is.
    String employeeNumber = (String)vo.getCurrentRow().getAttribute("EmployeeNumber");
    //ma String employeeNum = String.valueOf(employeeNumber.intValue());
    //ma Number employeeNumber = (Number)vo.getCurrentRow().getAttribute("EmployeeNumber");
    //ma String employeeNum = String.valueOf(employeeNumber.intValue());
    // Simply telling the transaction to commit will cause all the Entity Object validation
    // to fire.
    // Note: there's no reason for a developer to perform a rollback. This is handled by
    // the framework if errors are encountered.
    OAMessageStyledTextBean xSeq = (OAMessageStyledTextBean)mainRn.findIndexedChildRecursive("Seq");
    System.out.println("Seq=" + xSeq.getText(pageContext));
    am.invokeMethod("apply");
    // Indicate that the Create transaction is complete.
    TransactionUnitHelper.endTransactionUnit(pageContext, "jobperfCreateTxn");
    // Assuming the "commit" succeeds, navigate back to the "Search" page with
    // the user's search criteria intact and display a "Confirmation" message
    // at the top of the page.
    MessageToken[] tokens = { new MessageToken("EMP_NAME", employeeName),
    new MessageToken("EMP_NUMBER", employeeNumber) };
    OAException confirmMessage = new OAException("PER", "LAC_FWK_TBX_T_EMP_CREATE_CONF", tokens,
    OAException.CONFIRMATION, null);
    // Per the UI guidelines, we want to add the confirmation message at the
    // top of the search/results page and we want the old search criteria and
    // results to display.
    pageContext.putDialogMessage(confirmMessage);
    HashMap params = new HashMap(1);
    // Replace the current employeeNumber request parameter value with "X"
    params.put("employeeNumber", "employeeNumber");
    // IntegerUtils is a handy utility
    params.put("employeeNumber",IntegerUtils.getInteger(5));
    pageContext.forwardImmediately(
    "OA.jsp?page=/lac/oracle/apps/lac/jobperf/webui/jobperfPG",
    null,
    OAWebBeanConstants.KEEP_MENU_CONTEXT,
    null,
    params, //null,
    false, // retain AM
    OAWebBeanConstants.ADD_BREAD_CRUMB_YES);
    else if (pageContext.getParameter("Cancel") != null)
    am.invokeMethod("rollbackReview");
    // Indicate that the Create transaction is complete.
    TransactionUnitHelper.endTransactionUnit(pageContext, "jobperfCreateTxn");
    pageContext.forwardImmediately("OA.jsp?page=/lac/oracle/apps/lac/jobperf/webui/jobperfPG",
    null,
    OAWebBeanConstants.KEEP_MENU_CONTEXT,
    null,
    null,
    false, // retain AM
    OAWebBeanConstants.ADD_BREAD_CRUMB_NO);
    } // end processFormRequest()
    }

    Hi Tapash,
    Thanks for all of you guys(Tapash/Sumit/user550094) help. The sequence is working and also populating the values in the table when I do not have any validation checks imposed on it.
    If I add any validations as mentioned in the exercise for create page where it checks if the sequence can be updated while null and so on... and throws appropriate exception. I get error. That is the code that I mentioned above.
    Here is the validation code for EOImpl:
    As mentioned below in order for the code to compile and work I had to comment the "throw new OAAttrvalException". If I uncomment the
    "throw new OAAttrvalException" part, it gives me the following error while compiling:
    "Error(796,13): method getPrimarykey not found in class lac.oracle.apps.lac.jobperf.schema.server.jobperfEOImpl"
    public void setSeq(Number value)
    // Because of the declaritive validation that you specified for this attribute,
    // BC4J validates that this can be updated only on a new line, and that this,
    // mandatory attribute cannot be null. This code adds the additional check
    // of only allowing an update if the value is null to prevent changes while
    // the object is in memory.
    if (getSeq() != null)
    /* throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
    getEntityDef().getFullName(), //getSeq(), // EO name
    getPrimarykey(), // EO PK
    "Seq", // Attribute Name
    value, // Attribute value
    "AK", // Message product short name
    "FWK_TBX_T_EMP_ID_NO_UPDATE"); // Message name */
    if (value != null)
    // Seq ID must be unique. To verify this, check both the
    // entity cache and the database. In this case, it's appropriate
    // to use findByPrimaryKey() because you're unlikely to get a match, and
    // and are therefore unlikely to pull a bunch of large objects into memory.
    // Note that findByPrimaryKey() is guaranteed to check all employees.
    // First it checks the entity cache, then it checks the database.
    OADBTransaction transaction = getOADBTransaction();
    Object[] employeeKey = {value};
    EntityDefImpl empDefinition = jobperfEOImpl.getDefinitionObject();
    jobperfEOImpl Seq =
    (jobperfEOImpl) empDefinition.findByPrimaryKey(transaction, new Key(employeeKey));
    if (Seq != null)
    /* throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
    getEntityDef().getFullName(), // .getSeq(), // EO name
    getPrimaryKey(), // EO PK
    "Seq", // Attribute Name
    value, // Attribute value
    "AK", // Message product short name
    "FWK_TBX_T_EMP_ID_UNIQUE"); // Message name */
    // Note that this is the point at which the value is actually set on the EO cache
    // (during the scope of setAttributeInternal processing). If you don't make this
    // call after you perform your validation, your value will not be set correctly.
    // Also, any declarative validation that you define for this attribute is executed
    // within this method.
    setAttributeInternal(SEQ, value);
    } // end SetSeq
    I am sorry if I have confused you. I really did not mean to do it.
    Thanks,
    Ali

  • Using a single sequence value over multiple scripts (in a variable?)

    Hi all...
    I'm writing a number of scripts that insert rows into tables.
    To better explain my point, I'll paste a simple breakdown of the scripts here as that will be easier to understand...
    Script 1:
    INSERT INTO WORKGROUP_DEPARTMENTS(ID, DEPT_NAME, DEPT_TYPE)
    VALUES (SEQ_WGDPT.NEXTVAL, 'Staff', 3);
    Script 2:
    INSERT INTO WORKGROUP_SECTIONS(ID, SECT_NAME, WGDPT_ID)
    VALUES (SEQ_WGSEC.NEXTVAL, 'Staff 1',
    (SELECT ID FROM WORKGROUP_DEPARTMENTS
    WHERE DEPT_NAME = 'Staff'
    AND DEPT_TYPE = '3')
    Script 3:
    INSERT INTO WORKGROUPS(NAME, UNIT_TYPE, WGSEC_ID)
    VALUES ('Staff Room', 3,
    (SELECT ID FROM WORKGROUP_SECTIONS
    WHERE SECT_NAME = 'Staff 1')
    As you can see, in scripts 1 and 2 a new value is produced from a sequence (SEQ_WGDPT & SEQ_WGSEC respectively). Then, in scripts 2 & 3 (respectively) these values are inserted into another table.
    What I'm trying to figure out is: can I do the same thing here without having to include the horrible SELECT statements in scripts 2 & 3 in order to find the ID, which was produced by the sequence in the previous script?
    Unfortunately they do have to be separate scripts, and as such I can't call Sequence.CurrVal from a different script as other users may have used the sequence since it was used initially in the previous script. I could call it from the original calling script, and save it intop a variable, but I have no idea how to - even if it is the right idea!
    I tried to insert the sequence value into a variable a la PL/SQL so that I could call this variable from the next script, but failed miserably as I'm rubbish!
    Any help would be great. Thanks.

    You can use PL/SQL, for example:
    SQL> desc t
    Name                                      Null?    Type
    ID                                                 NUMBER
    NAME                                               VARCHAR2(10)
    SQL> desc t1
    Name                                      Null?    Type
    ID                                                 NUMBER
    NAME                                               VARCHAR2(10)
    ID1                                                NUMBER
    SQL> desc t2
    Name                                      Null?    Type
    ID                                                 NUMBER
    NAME                                               VARCHAR2(10)
    ID2                                                NUMBER
    SQL> create sequence seq_1;
    Sequence created.
    SQL> declare
      2   prev_id number;
      3  begin
      4   insert into t values(seq_1.nextval,'A')
      5   returning id into prev_id;
      6   insert into t1 values(seq_1.nextval,'B',prev_id)
      7   returning id into prev_id;
      8   insert into t2 values(seq_1.nextval,'C',prev_id);
      9  end;
    10  /
    PL/SQL procedure successfully completed.
    SQL> select * from t;
            ID NAME
             1 A
    SQL> select * from t1;
            ID NAME              ID1
             2 B                   1
    SQL> select * from t2;
            ID NAME              ID2
             3 C                   2
    Rgds

  • How to get sequence value on click of button in OAF Page

    Hi all,
    I have a requirement to get a field called Bankrefernece number populated with sequence value on click of apply button ; i mean inserting new record in database for new transaction.
    Sequence Value should be something like this:
    Example
    No     Transfer Date     Bank Reference Number
    (DDMMYY_999)
    1     24-Oct-2010     241010_001
    2     24-Oct-2010     241010_002
    3     25-Oct-2010     251010_001
    means every day sequence should start with the date initials.
    Kindly give your valuable input.
    Thanks
    Sims
    Edited by: sims on Jan 4, 2011 11:22 PM

    sims wrote:
    Hi Anil,
    Its a standard page & i want it on click of apply button but my question is when i click apply button it navigates to other page..is it possible in such scenario to extend the controller.
    Thnx for ur suggestion
    SimsThat is not an issue, you can extend the controller of that page and get the value of sequence and set it to the VO attribute.
    Thanks
    --Anil
    http://oracleanil.blogspot.com

  • Getting error while reset sequence value

    i hve created two table. and a sequence for other table. i want to do that when i insert into a first table, entries of other table should be deleted and sequence value should reset to 1. For that i have executed the following sql code
    but getting the error:
    create or replace Trigger m_sale_ainsert_trig
    after insert on m_sale_bill
    for each row
    begin
    DELETE FROM M_TEMP;
    <<COLUMN_SEQUENCES>>
    BEGIN
    Alter Sequence M_TEMP_SEQ Restart with 1;
    END COLUMN_SEQUENCES;
    end;
    Alter Trigger m_sale_ainsert_trig enable;
    Warning: execution completed with warning
    Trigger m_sale_ainsert_trig Compiled.
    Alter Trigger m_sale_ainsert_trig succeeded.
    5/4 PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
    ( begin case declare exit for goto if loop mod null pragma
    raise return select update while with <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> <<
    continue close current delete fetch lock insert open rollback
    savepoint set sql execute commit forall merge pipe purge
    pls rectify it!!!!! what are the mistakes in this code?
    Edited by: JKMourya on Mar 21, 2013 10:55 AM

    JKMourya wrote:
    i hve created two table. and a sequence for other table. i want to do that when i insert into a first table, entries of other table should be deleted and sequence value should reset to 1. For that i have executed the following sql code
    but getting the error:
    create or replace Trigger m_sale_ainsert_trig
    after insert on m_sale_bill
    for each row
    begin
    DELETE FROM M_TEMP;
    <<COLUMN_SEQUENCES>>
    BEGIN
    Alter Sequence M_TEMP_SEQ Restart with 1;
    END COLUMN_SEQUENCES;
    end;
    Alter Trigger m_sale_ainsert_trig enable;
    Warning: execution completed with warning
    Trigger m_sale_ainsert_trig Compiled.
    Alter Trigger m_sale_ainsert_trig succeeded.
    5/4 PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
    ( begin case declare exit for goto if loop mod null pragma
    raise return select update while with <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> <<
    continue close current delete fetch lock insert open rollback
    savepoint set sql execute commit forall merge pipe purge
    pls rectify it!!!!! what are the mistakes in this code?
    Edited by: JKMourya on Mar 21, 2013 10:55 AMDDL inside PL/SQL is NOT allowed
    you must (ab)use EXECUTE IMMEDIATE

  • Golden Gate Sequence Value replication?

    Hi all,
    I have searched the web, and read the Golden Gate documentation but I've found mixed answers.
    I'm just trying to ascertain for certain whether it's possible to automatically replicate sequence values in a bi-directional configuration. Both databases will be identical and both will be 11gR2 with the latest version of GG.
    If it is not possible to automatically increment sequences in a bi-directional configuration, what are the best practices for maintaing them?
    One option is the alternate sequences on each database, one with even values (for example) and one with odd values, but this requires deployment of new sequences on both databases, something we were hoping would be taken care of by the replication. (yes the sequence creation can be taken care of but the value is not incremented on the target database).
    another way that we thought of off the top of our heads is to have an on insert trigger (we only use sequences to generate surrogate keys) which will select nextval from the target database via a db link, but this seems somewhat cumbersome.
    What is best practice?

    Use sequence parameter... here is from Golden gate document:
    SEQUENCE
    Valid for Extract
    Use the SEQUENCE parameter to extract sequence values from the transaction log forpropagation to a GoldenGate trail and delivery to another database. Currently, GoldenGate supports sequences for the Oracle database.
    NOTE DDL support for sequences (CREATE, ALTER, DROP, RENAME) is compatible with, but not required for, replicating sequence values. To replicate just sequence values, you do not need to install the GoldenGate DDL support environment. You can just use the SEQUENCE parameter.
    GoldenGate ensures that the values of a target sequence are:
    ● higher than the source values if the increment interval is positive
    ● lower than the source values if the increment interval is negative
    Depending on the increment direction, Replicat applies one of the following formulas as a test when it performs an insert:
    source_highwater_value + (source_cache_size * source_increment_size * source_RAC_nodes) <= target_highwater_value
    Or...
    source_highwater_value + (source_cache_size * source_increment_size * source_RAC_nodes) >= target_highwater_value
    If the formula evaluates to FALSE, the target sequence is updated to be higher than the source value (if sequences are incremented) or lower than the source value (if sequences are decremented). The target must always be ahead of, or equal to, the expression in the parentheses in the formula. For example, if the source highwater value is 40, and CACHE is 20, and the source INCREMENTBY value is 1, and there are two source RAC nodes, the target highwater value should be at least 80:
    40 + (20*1*2) <80
    If the target highwater value is less than 80, GoldenGate updates the sequence to increase the highwater value, so that the target remains ahead of the source. To get the current highwater value, perform this query:
    SELECT last_number FROM all_sequences WHERE sequence_owner=upper('SEQUENCEOWNER') AND sequence_name=upper('SEQUENCENAME');

  • Need to populate sequence value in a field after insert in oaf page

    Hi All,
    I have a custom OAF insert page in that i need to populate a sequence value to a field once the data inserted successfully to the table.
    so for that i followed the below approach.
    1>Created a sequence in database.
    2>In the EOImpl java file in the setter method for the respective field have written below code.
        public void setContainid(Number value) {
            if (value == null) {
                    OADBTransaction t = getOADBTransaction();
                    value = t.getSequenceValue("XXXXX_CONTAIN_SEQ");
            setAttributeInternal(CONTAINID,value);  
    But still i am not able to populate the sequence value for the field in my oaf page,please help me out on thsi.
    Thanks

    Hi,
    Write this logic in create method of EOImpl:
      public void create(AttributeList attributeList)
        super.create(attributeList);
        OADBTransaction transaction = getOADBTransaction();
        Number contID = transaction.getSequenceValue("XXXXX_CONTAIN_SEQ");
        setContainId(contID);
    --Sushant

  • How to get sequence value?

    hi,
    i'm trying to store sequence's value into a variable... smth like this:
    create or replace function my_funct() as integer
    is
    begin
    return my_sequence.currval;
    end;
    and "return my_sequence.currvalue" doesn't seem to work...
    also i'would like to store that value into a variable, like:
    is
    i integer;
    begin
    i := my_sequence.currval;
    end;
    this also doesn't seem to work
    regards

    Hi,
    You will using this method to store sequence value to variable
    declare
    i number;
    begin
    select sq.currval into i from dual;
    dbms_output.put_line(i);
    end;
    Anbudan,
    Radha.

  • Prevent skipping sequence value?

    We created a sequenential PK populated from a another database table. We take value from this table and update last sequence value.
    ( IN ADF faces 11g app)
    But if an error in commit processing of page, sequence is populated on the screeen. Error can be formatting error, validation error or etc
    Then we correct format mistakes a new number is popolated at PK field.
    So some values are skipped.
    How can we prevent skipping sequence value? it is very important issue in our bussiness case.
    Thanks...

    We write code in doDML metdod of entity object as following mypackage.getmaxno().
    We can posponed getting max no formatting till commit time. Where we need to write code to prevent the gap ?
    protected void doDML(int operation, TransactionEvent e) {
    if(operation==DML_INSERT){
    String sql="{?= call mypackage.getmaxno()}";
    CallableStatement cs=getDBTransaction().createCallableStatement(sql,0);
    try {
    cs.registerOutParameter(1,OracleTypes.VARCHAR);
    cs.execute();
    String MaxNo=cs.getString(1);
    setMaxNo(evrakNo);
    createDoc();
    } catch (SQLException f) {f.printStackTrace();}
    super.doDML(operation, e);
    }

  • Last identity \ sequence value

    Hello,
    I have a little problem in some code I have written.
    I have a database trigger that sequences rows for me on a transaction being entered into the database table.
    However, as the return value of the procedure I have written I want this value to be returned.
    How do I get the PK (eg sequence number) of the last record that was placed into the database table.
    I am guessing that there is some form of sequence.last construct but I can't help being concerned by concurency issues (eg will the last sequence value always be the sequence that my trigger used)
    Any advice will be gratefully recieved.
    Regards

    You'll have to figure out the details, but this is why Larry gave us the RETURNING clause.
    SQL> CREATE TABLE apc1 (pk1 NUMBER, col1 NUMBER);
    Table created.
    SQL> CREATE SEQUENCE apc_pk;
    Sequence created.
    SQL> CREATE TRIGGER apc_bir BEFORE INSERT ON apc1 FOR EACH ROW
      2  BEGIN
      3     SELECT apc_pk.NEXTVAL INTO :NEW.pk1
      4     FROM   dual;
      5  END;
      6  /
    Trigger created.
    SQL> var x NUMBER
    SQL> BEGIN
      2     INSERT INTO apc1 (col1)
      3     VALUES (32)
      4     RETURNING pk1 INTO :x;
      5  END;
      6  /
    PL/SQL procedure successfully completed.
    SQL> print x
             X
             1
    SQL> SELECT * FROM apc1;
           PK1       COL1
             1         32
    SQL> Cheers, APC

  • Need to get sequence value in another column in oracle

    Hi ALL,
    I have sql query as below
    select header_id,order_number from oe_order_headers_all.
    and data it is displaying as
    heder_id     order_number
    111            500001
    121            500400
    I need to display  another field with some sequence value like as below
    id     heder_id     order_number
    1      111                    500001
    2      121                    500400
    so how to get sequence value in another column please help me on this.
    Thnaks

    You can just use ROWNUM Pseudocolumn
    select rownum id, header_id,order_number from oe_order_headers_all

  • Inserting oracle sequence values

    hI
    Do i need to do a select sequence.nextval from dual
    before i insert the next sequence value into the table
    For eg i tried using the foll insert statement but i get an invalid number exception
    insert into parts(PARTS'DATABASE.PARTNOSEQ.NEXTVAL',"+PARTNO+")
    But i get the above exception.I dont do a select now.
    Thanks
    Arn

    Hi
    I tried doing the following trying to insert sequence values but I still get an invalid get Column error.
    sql4 = "select PART_SEQ.NEXTVAL FROM DUAL";
    ResultSet rs3 = stmt2.executeQuery(sql4);
    while (rs3.next())
    seqVal = rs.getInt("PART_SEQ");
    rs3.close();
    for(int i=0; i<=count; i++)
    { // for loop
         sql3 = "Update part " +
         " SET part_mfr = '"+mfgcodeStr+"' ,
         " part_id = "+seqVal+"," +
         " WHERE invoiceno = '"+invoicenoStr+"' ";
    Thanks
    arn

  • Insert multiple rows in on table and retreive sequence values

    Hello,
    I'm searching a way to insert several rows in a table that needs a sequence and retreive its.
    For one row i use ExecuteScalar method with the following SQL is :
    INSERT INTO MY_TABLE(MY_PK)
    VALUES(SEQ_MY_TABLE.NEXTVAL) RETURNING MY_PK INTO :MY_PARAMETER
    The aim is to insert several rows at one time. Currently I execute this SQL :
    INSERT INTO MY_TABLE(MY_PK, MY_VALUE)
    SELECT SEQ_MY_TABLE.NEXTVAL, MY_VALUE
    FROM (
    SELECT 0 MY_VALUE FROM DUAL UNION ALL
    SELECT 1 MY_VALUE FROM DUAL
    This query works well but i'm wondering how to retreive all sequence values generated by this query.
    Is it possible and how ?
    Thank you.
    Sebastien

    I tried this :
    string sql = "INSERT INTO MY_TABLE(MY_PK, MY_VALUE) " +
    "SELECT SEQ_MY_TABLE.NEXTVAL MY_PK, MY_VALUE FROM ( " +
    "SELECT 0 MY_VALUE UNION ALL " +
    "SELECT 1 MY_VALUE) " +
    "RETURNING MY_PK BULL COLLECT INTO : RETURN_IDS";
    using(var manager = myFactory.CreateDbManager()) // Initializes the connection and encapsulates ADO objects
    manager.SetCommand(sql);
    var cmd = (OracleCommand)manager.Command;
    cmd.ArrayBindCount = 2;
    var p = new OracleParameter();
    p.DbType = DbType.Int64;
    p.ParameterName = "RETURN_IDS";
    p.Direction = ParameterDirection.Output;
    p.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
    p.Size = 2*sizeof (long);
    cmd.Parameters.Add(p);
    cmd.ExecuteNonQuery();
    var result = (Oracle.DataAccess.Types.OracleDecimal[])p.Value;
    But I have an error ORA-00933 that indicates that the query is wrong at "RETURNING MY_PK".
    .......................................................................................................^
    Edited by: CITnDev on 1 août 2012 13:00
    Edited by: CITnDev on 1 août 2012 15:10

  • Inserting sequence value from JDBC and getting the same value back

    Hi: Gurus I have a table whose primary key is a sequence. I wonder how to make sure I get the same sequence value back for current transaction so I update the other table whose foreign key is the sequence value from first table.
    E.g lets say I do this
    String query_insert = INSERT INTO table1 (column1, ....) VALUES (HIGHLIGHT_ID_SEQ.nextval, ...);
    pstmt = con.prepareStatement(query_insert);
    pstmt.executeUpdate();
    How I make sure no other transaction update the sequence value so I can read the last inserted sequence value and update the second table with this value
    String query_select = "SELECT HIGHLIGHT_ID_SEQ.currval FROM DUAL";
    pstmt = con.prepareStatement(query_select);
    Regards,
    Rashid.

    <rant>No version again. I wonder why people requiring help want to stay anonymous and never want to type their version, only 4 digits. In this case, jdbc, not only the version of the driver is important, but also it's type. Waving a magic wand again? </rant>
    Look up the returning into clause of the insert statement in the sql reference manual for your version.
    Sybrand Bakker
    Senior Oracle DBA

  • Sequence value

    Hi all,
    I want to see current sequence value other than issuing sequence.currval. Although first time you can't see the current value of sequence without issuing sequence.nextval. only after issuing sequence.nextval you can see the current value of it. So how I can see the current value of sequence for the first time after start the database instance. Is it possible or not.

    jeneesh wrote:
    select * from dba_sequences where sequence_name = 'YOUR_SEQUENCE_NAME'
    This will not work if sequence has CACHE (default is CACHE 20).
    SY.

  • OGG Bidirectional Sequence value replication - HELP

    Hi OGG Experts,
    I have a Bi_Directional config in my systems and as per the OGG Doc, Sequence value replication is not Possible in Bi-Directional Config.
    1) Why is it, I can't do sequence value replication in Bi-Directional config.
    2) If I can do, what are all the ways?
    3) I found odd and even sequence method but is it preferable to use this method. IF not, what are other ways to accomplish it.
    ~ Lother

    On the source, the sequence value is in the redo stream. When it gets sent to the target, why generate another sequence value for something that is already present in what replicat is going to apply on the target?
    Odd/even or a staggered order (start with 1,2,3 and increment by 3) for more than two is the way to go.

Maybe you are looking for