Currval pf a sequence

If I want to get the currval of a sequence, will it be OK to do it by saying:
select A_seq.nextval-1 into :new.B from dual; ?
Cause I've read that in order to get currval, nextval need to be called at least once. Will this work?
Thanks

As SomeoneElse wrote you can not do it but I would like to add some explanation.
The question you need to ask yourself is what it is you are trying to do: I think you are unclear. CURRVAL gives you the current value in your session. If you have not called NEXTVAL then no value exists.
If you are looking for the last value used by someone else then you need to understand that Oracle is not single-user software. It is possible that as many as 300,000+ users are simultaneously connected and using the same sequence. What value would you want? And why?
Oracle's quite rational response is to provide a mechanism that answers the only logically consistent question.

Similar Messages

  • Sequence Last Number doesn't match with currval

    Hi,
    I have a sequence and i am using that in a procedure to insert records.Often the procedure throws error like primary key violated.
    When i checked the last number used by the sequence it gave me as 27331 and the currval of the sequence as 27312.
    Please advice us to rectify this.

    746379 wrote:
    Hi,
    I have a sequence and i am using that in a procedure to insert records.Often the procedure throws error like primary key violated.
    When i checked the last number used by the sequence it gave me as 27331 and the currval of the sequence as 27312.
    Please advice us to rectify this.First make sure that you understand the difference between a primary key and a sequence.
    A sequence is just a number generator. Oracle guarantees that the sequence will give you a new unique number each time that you call NEXTVAL. If the sequence is cycling then it can even generate the same number again after some time but this is rarely the case.
    A primary key is a constaint on your table that requires all values in the column to be unique and not null.
    When you get an primary key violated error then you just tried to insert a value that was already there in the table.
    Some scenarios might be the reason for this.
    <li>You insert a row using the sequence. You insert a new row using the same number again without fetching it from NEXTVAL (e.g. using currval instead of nextval, or not updating a variable that holds the new ID,...)</li>
    <li>Somebody else already inserted an ID without using the sequence</li>
    <li>A variation is when you import data from another database and resetted the sequences</li>
    <li>There is some test data in your tables. The test data was inserted in a high ID range to separate it from the real data. Your sequence just reached this range.</li>

  • Auto-numbering sequence from last number used

    Is there a way to set the Filename Template Editor and the Text Template Editor to automatically start numbering a batch of images from the latest number used?
    At present in Editor, one has to set the Start Number manually. I am using this feature on photos that were imported into LR long ago and am now getting around to editing, processing, cataloguing them. Part of that process for me is renaming them, giving each a custom+sequence Filename, for example "DDOH-3256".
    The way the text editor is set up now, I have to remember what I was working on most recently, find it, check what the last sequence number was in that batch, then set the next available sequence number in the Text Template Editor.
    I used to use IView Media Pro and it had a lot more naming and re-naming conventions, including. It would be great if LR had the same options.
    Thanks for any help or feedback,
    Esther
    Lightroom v1.4.1
    Mac OS 10.5.2 Leopard
    iMac 20" monitor
    2.4 GHz Intel Core 2 Duo
    2 GB DDR2 SDRAM

    746379 wrote:
    Hi,
    I have a sequence and i am using that in a procedure to insert records.Often the procedure throws error like primary key violated.
    When i checked the last number used by the sequence it gave me as 27331 and the currval of the sequence as 27312.
    Please advice us to rectify this.First make sure that you understand the difference between a primary key and a sequence.
    A sequence is just a number generator. Oracle guarantees that the sequence will give you a new unique number each time that you call NEXTVAL. If the sequence is cycling then it can even generate the same number again after some time but this is rarely the case.
    A primary key is a constaint on your table that requires all values in the column to be unique and not null.
    When you get an primary key violated error then you just tried to insert a value that was already there in the table.
    Some scenarios might be the reason for this.
    <li>You insert a row using the sequence. You insert a new row using the same number again without fetching it from NEXTVAL (e.g. using currval instead of nextval, or not updating a variable that holds the new ID,...)</li>
    <li>Somebody else already inserted an ID without using the sequence</li>
    <li>A variation is when you import data from another database and resetted the sequences</li>
    <li>There is some test data in your tables. The test data was inserted in a high ID range to separate it from the real data. Your sequence just reached this range.</li>

  • About runtime sequence creation and view dare pre commmit.

    Dear All,
    My 2 New Question are:
    1)Could Oracle suggest to create sequence(DDL) from run-time.That means I need(My client requirement) regenerate of sequence(I know it is possible by cycle but i don't know MAX value when it will cycle)as monthly or a specific time so I want to drop sequence and create sequence by a)Programmetically runtime
    b) Oracle scheduler runtime .
    Have any good and better Idea? Any risk factor?
    Note that at a time possibly more than 100 users will data entry with our software.
    2)My New query is Could I view table data which was not yet COMMITTED from other session-other user.
    Regards and Thanking you,
    ZAKIR
    Analyst ,
    SynesisIT,
    www.Synesisit.com
    =====

    I tried that, but there are too many trouble.
    For only references.
    -- Usage
    Procedures
     execute periodic_seq.seq_def   create sequence
     execute periodic_seq.seq_undef drop sequence
    Functions
      periodic_seq.nextvalue
       get nextval of specified sequence
      periodic_seq.currvalue
       get currval of specified sequence
    seq_def
     in_seq_name varchar2 (30)
        sequence name (current schema)
     in_trunc_unit varchar2
      'yyyy','mm','dd','hh24','mi' : format on trunc(date)
    seq_def
     in_owner varchar2 (30)
      schema name
     in_seq_name varchar2 (30)
      sequence name
     in_trunc_unit varchar2
      'yyyy','mm','dd','hh24','mi' : format on trunc(date)
     incr_by integer (default:1)
      increment by
     start_with integer (default:1)
      start with
     maxvalue integer (default:to_number('1e27'))
      maxvalue
     minvalue integer (default:1)
      minvalue
     cycle varchar2 (default:'N')
      'Y':cycle/'N':nocycle
     cache integer (default:20)
      cache
     time_order varchar2 (default:'N')
      'Y':order/'N':noorder
    seq_undef
     in_seq_name varchar2 (30)
        sequence name (current schema)
    seq_undef
     in_owner varchar2 (30)
      schema name
     in_seq_name varchar2 (30)
      sequence name
    nextvalue
     in_seq_name varchar2 (30)
        sequence name (current schema)
    nextvalue
      in_owner varchar2 (30)
      schema name
     in_seq_name varchar2 (30)
      sequence name
    currvalue
     in_seq_name varchar2 (30)
        sequence name (current schema)
    currvalue
      in_owner varchar2 (30)
      schema name
     in_seq_name varchar2 (30)
      sequence name
    -- Source --
    -- Control table
    create table cycle_seq_ctrl
    (sequence_name varchar2(30) not null
    ,min_value integer
    ,max_value integer
    ,increment_by integer not null
    ,cycle_term varchar(10) default('dd') not null
    ,last_number integer not null
    ,reset_time date
    ,prev_nextval integer not null
    ,constraint pkey_cycle_seq_ctrl primary key (sequence_name)
    organization index
    create or replace
    package cycle_seq
    authid current_user
    is
    function nextvalue
    (seq_name varchar2
    ,in_date date := sysdate
    ) return integer
    function currvalue
    (seq_name varchar2
    ) return integer
    procedure seq_def
    (seq_name varchar2
    ,cycleterm varchar2 := 'DD' /* Defaults : reset by a day */
    ,incr_by integer := 1
    ,start_with integer := 1
    ,maxvalue integer := to_number('1e27')
    ,minvalue integer := 1
    procedure seq_undef
    (seq_name varchar2
    end; -- package cycle_seq
    create or replace
    package body cycle_seq
    is
      type currval_tab_type is table of integer index by varchar2(30);
      currval_tab currval_tab_type;
    function nextvalue
    (seq_name varchar2
    ,in_date date := sysdate
    ) return integer
    is
    pragma autonomous_transaction;
      timeout_on_nowait exception;
      timeout_on_wait_sec exception;
      pragma exception_init(timeout_on_nowait, -54);
      pragma exception_init(timeout_on_wait_sec, -30006);
      p_seqname cycle_seq_ctrl.sequence_name%type;
      p_ctrl cycle_seq_ctrl%rowtype;
      p_currtime date;
      p_nextval integer;
    begin
      p_currtime := in_date;
      p_seqname := upper(trim(seq_name));
      select *
        into p_ctrl
        from cycle_seq_ctrl
       where sequence_name = p_seqname
      for update wait 1
      if (p_ctrl.cycle_term<>'SS') then
        p_currtime := trunc(p_currtime,p_ctrl.cycle_term);
      end if;
      -- need to reset
      if (p_ctrl.reset_time < p_currtime) then
        if (p_ctrl.increment_by > 0) then
          p_nextval := p_ctrl.min_value;
        elsif (p_ctrl.increment_by < 0) then
          p_nextval := p_ctrl.max_value;
        else
          p_nextval := p_ctrl.last_number;
        end if;
        update cycle_seq_ctrl
          set last_number = p_nextval
             ,reset_time = p_currtime
             ,prev_nextval = last_number + increment_by
        where sequence_name = p_seqname
        currval_tab(p_seqname) := p_nextval;
        commit;
        return p_nextval;
      end if;
      -- already reseted (in a same second)
      if (p_ctrl.reset_time = p_currtime) then
        p_nextval := p_ctrl.last_number + p_ctrl.increment_by;
        update cycle_seq_ctrl
          set last_number = p_nextval
        where sequence_name = p_seqname
        currval_tab(p_seqname) := p_nextval;
        commit;
        return p_nextval;
      -- already reseted
      else
        p_nextval := p_ctrl.prev_nextval + p_ctrl.increment_by;
        update cycle_seq_ctrl
          set prev_nextval = p_nextval
        where sequence_name = p_seqname
        currval_tab(p_seqname) := p_nextval;
        commit;
        return p_nextval;
      end if;
    exception
      when no_data_found then
        raise_application_error(-20800,
           'cycle_seq.seq_def('''||seq_name
           ||''') has not been called.');
      when timeout_on_nowait or timeout_on_wait_sec then
        raise_application_error(-20899,
           'cycle_seq.nextvalue('''||seq_name
           ||''') is time out.');
      when others then
        raise;
    end
    function currvalue
    (seq_name varchar2
    ) return integer
    is
      p_seqname cycle_seq_ctrl.sequence_name%type;
    begin
      p_seqname := upper(trim(seq_name));
      return currval_tab(upper(seq_name));
    exception
      when no_data_found then
        raise_application_error(-20802,
           'cycle_seq.nextvalue('''
           ||seq_name||''') has not been called in this session.');
      when others then
        raise;
    end
    procedure seq_def
    (seq_name varchar2
    ,cycleterm varchar2 := 'DD'
    ,incr_by integer := 1
    ,start_with integer := 1
    ,maxvalue integer := to_number('1e27')
    ,minvalue integer := 1
    is
      p_seqname cycle_seq_ctrl.sequence_name%type;
      p_currtime date;
      p_cycleterm cycle_seq_ctrl.cycle_term%type;
    begin
      p_currtime := sysdate;
      p_seqname := upper(trim(seq_name));
      p_cycleterm := upper(trim(cycleterm));
      if (p_cycleterm<>'SS') then
        p_currtime := trunc(p_currtime,cycleterm);
      end if;
      insert into cycle_seq_ctrl
        (sequence_name
        ,min_value
        ,max_value
        ,increment_by
        ,cycle_term
        ,last_number
        ,reset_time
        ,prev_nextval
      values
        (p_seqname
        ,minvalue
        ,maxvalue
        ,incr_by
        ,p_cycleterm
        ,start_with - incr_by
        ,p_currtime
        ,start_with - incr_by
      commit; -- Because this is as like a DDL
    exception
      when dup_val_on_index then
        raise_application_error(-20955,
           'already defined with '
          ||'cycle_seq.seq_def('''||seq_name||''')');
      when others then
        raise;
    end
    procedure seq_undef
    (seq_name varchar2
    is
      p_seqname cycle_seq_ctrl.sequence_name%type;
    begin
      p_seqname := upper(trim(seq_name));
      delete from cycle_seq_ctrl
      where sequence_name = p_seqname
      commit; -- Because this is as like a DDL
    end
    end; -- package body cycle_seq
    /

  • Auto sequencing

    Hi,
    I am new to Oracle but have experience with the procedural languages in MS SQL Server and Sysbase and in the past have used these languages extensively.
    I often use a number for my PK and get the database to increment that for me. In MS SQL Server you denote this field as [Identity=Yes] and you can set the seed (ie where to start the sequence) as well. Now in oracle as far as I can see I have to do this, as follows:
    DROP SEQUENCE INDEM_SIGS_SEQ;
    CREATE SEQUENCE INDEM_SIGS_SEQ MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE;
    CREATE TABLE INDEMNITY_SIGNATORIES (
    IS_NO NUMBER(6) NOT NULL ENABLE,
    ... more fields
    CONSTRAINT PK_INDEMNITY_SIGNATORIES primary key (IS_NO),
    CONSTRAINT ... more constraints
    CREATE OR REPLACE TRIGGER BI_INDEM_SIGS
    before insert on INDEMNITY_SIGNATORIES
    for each row
    begin
    select INDEM_SIGS_SEQ.nextval into :NEW.IS_NO from dual;
    end;
    ALTER TRIGGER BI_INDEM_SIGS ENABLE;
    Now this seems a long-winded way of doing something that in SQL Server I just need to change a property value to do. But fair enough I only have to do it once for each table that has a sequential prime key, but if anyone is looking at this and can think of an easier way then please let me know.
    The next thing is that you sometimes get the situation when you insert a record and that you need the vaue of the prime key of the record you have just inserted. So you can then insert or update records in another tables that have this number possibly as a FK in other tables.
    In SQL Server I would do this as follows:
    INSERT INTO contacts (contact_type, first_name, surname, secretary, salutation, title, email, tel, mobile, fax, xmas_card, notes, created, modified)
    VALUES (@contact_type, @first_name, @surname, @secretary, @salutation, @title, @email, @tel, @mobile, @fax, @xmas_card, @notes, GetDate(), GetDate());
    SELECT contact_no FROM contacts WHERE (contact_no = @@IDENTITY);
    I hope this is clear and that someone can help.

    If you want the primary key column to be populated automatically, the trigger you've posted is correct. Lots of folks prefer just to put the sequence in the actual insert statement, i.e.
    INSERT INTO indemnity_signatories( is_no, other_columns )
      VALUES( indem_sigs_seq.nextval, other_values );You can get that sequence value back either using the RETURNING clause or using the CURRVAL of the sequence, i.e.
    INSERT INTO indemnity_signatories( other_columns )
      VALUES( other_values )
      RETURNING is_no INTO my_local_is_no_variable;or
    SELECT indem_sigs_seq.currval
      INTO my_local_is_no_variable
      FROM dual;Justin

  • Sequence initilization

    1) Why initialization of the sequence with NEXTVAL is required? when we create a sequence Before we use CURRVAL for a sequence in our session, we must first initialize the sequence with NEXTVAL otherwise it will give an error as 'ORA-08002: sequence SEQ1.CURRVAL is not yet defined in this session' .
    2)Where exactly on the disk the sequence nextval is stored if we are using a nocache option while creating a sequence. To check the sequence related data I queried "SYSTEM.SEQ" Tablespace, I can describe this table but cannot see the contents giving an error as 'ORA-00942: table or view does not exist'.

    Welcome to the forum!
    Whenever you post provide your 4 digit Oracle version (result of SELECT * FROM V$VERSION
    >
    1) Why initialization of the sequence with NEXTVAL is required? when we create a sequence Before we use CURRVAL for a sequence in our session, we must first initialize the sequence with NEXTVAL otherwise it will give an error as 'ORA-08002: sequence SEQ1.CURRVAL is not yet defined in this session' .
    >
    The reason is because a sequence can be used by more than one session. Each session first needs to get a sequence number before it can use it. When you (a session) use NEXTVAL to 'get' a sequence number Oracle increments the number (using the INCREMENT BY valuel) so the next session using NEXTVAL won't get your number.
    So CURRVAL does not return the current sequence value that is stored in the SYS.SEQ$ table; CURRVAL returns the current value of the sequence that your session is using. If it returned the actual value in the SEQ$ table that value might be used by someone else using NEXTVAL and then if you used it you would be using a duplicate.
    >
    2)Where exactly on the disk the sequence nextval is stored if we are using a nocache option while creating a sequence. To check the sequence related data I queried "SYSTEM.SEQ" Tablespace, I can describe this table but cannot see the contents giving an error as 'ORA-00942: table or view does not exist'.
    >
    The actual table is the SYS.SEQ$ table. The xxx_SEQUENCES views (e.g. ALL_SEQUENCES, USER_SEQUENCES) are base on that table.
    If the sequence uses NOCACHE then any session using NEXTVAL causes the SYS.SEQ$ table to be accessed and incremented. That is a VERY inefficient serial process and can severely affect performance in a multiuser environment.
    When you use CACHE (e.g. CACHE 100) then the first session that uses NEXTVAL causes Oracle to load 100 values values into memory and the next NEXTVAL that any session issues will get a number from that memory cache. Since memory accesses are very fast this minimizes the performance impact.
    select * from all_sequences where sequence_name = 'DEPARTMENTS_SEQ'
    SEQUENCE_OWNER,SEQUENCE_NAME,MIN_VALUE,MAX_VALUE,INCREMENT_BY,CYCLE_FLAG,ORDER_FLAG,CACHE_SIZE,LAST_NUMBER
    HR,DEPARTMENTS_SEQ,1,9990,10,N,N,0,280See CREATE SEQUENCE in the SQL Language doc
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_6015.htm
    But be aware that this quote from the documentation is misleading
    >
    After a sequence is created, you can access its values in SQL statements with the CURRVAL pseudocolumn, which returns the current value of the sequence, or the NEXTVAL pseudocolumn, which increments the sequence and returns the new value.
    >
    As you already know, in spite of what that quote says you CANNOT use CURRVAL until after you have used NEXTVAL.

  • Four fundamental questions on Sequences

    DB version:11G
    Question *1* and *2*:
    To determine the current value of a Sequence i try
    SQL> SELECT  SEQ_SHP_HDR.CURRVAL FROM DUAL;
    SELECT  SEQ_SHP_HDR.CURRVAL FROM DUAL
    ERROR at line 1:
    ORA-08002: sequence SEQ_SHP_HDR.CURRVAL is not yet defined in this
    sessionI know that if i use
    SELECT  SEQ_SHP_HDR.NEXTVAL FROM DUAL;i can get CURRVAL from the sequence. But that will increment the sequence.
    So I tried looking at user_sequences.last_number . But user_sequences.last_number was showing 552 when the actual currval was 545 !
    Why am i getting the above error (SEQ_SHP_HDR.CURRVAL is not yet defined in this session) and how can one accurately determine
    the currval of a sequence without incrementing it using NEXTVAL?
    Question *3*.
    To Increment a sequence, one should use
    alter sequence <sequencename> increment by n ;Right?
    Do you guys use
    SELECT  <sequencename>.NEXTVAL FROM DUAL;to increment SEQUENCES?
    Question *4*.
    I was trying to increment a sequence. After the ALTER statement, the sequence didn't get incremented. I had to issue a NEXTVAL call to actually get this reflected. Why is this happening?
    SQL> select * from v$version where rownum=1;
    BANNER
    Oracle Database 11g Release 11.1.0.7.0 - 64bit Production
    SQL> CREATE SEQUENCE myseq
      2    START WITH 1
      3    NOMAXVALUE;
    Sequence created.
    SQL> select myseq.nextval from dual;
       NEXTVAL
             1
    SQL> alter sequence myseq increment by 7;
    Sequence altered.
    SQL> select myseq.currval from dual;
       CURRVAL
             1
    SQL> select myseq.nextval from dual;
       NEXTVAL
             8
    SQL> select myseq.currval from dual;
       CURRVAL
             8
            

    Steve_74 wrote:
    DB version:11G
    Question *1* and *2*:
    To determine the current value of a Sequence i try
    SQL> SELECT  SEQ_SHP_HDR.CURRVAL FROM DUAL;
    SELECT  SEQ_SHP_HDR.CURRVAL FROM DUAL
    ERROR at line 1:
    ORA-08002: sequence SEQ_SHP_HDR.CURRVAL is not yet defined in this
    sessionI know that if i use
    SELECT  SEQ_SHP_HDR.NEXTVAL FROM DUAL;i can get CURRVAL from the sequence. But that will increment the sequence.
    So I tried looking at user_sequences.last_number . But user_sequences.last_number was showing 552 when the actual currval was 545 !
    Why am i getting the above error (SEQ_SHP_HDR.CURRVAL is not yet defined in this session) and how can one accurately determine
    the currval of a sequence without incrementing it using NEXTVAL?You cant get the CURRVAL unless you execute the NEXTVAL alteast once in your session. And you cant use the user_sequences.last_number if the CACHE is enabled.
    Question *3*.
    To Increment a sequence, one should use
    alter sequence <sequencename> increment by n ;Right?WRONG!! You have actually altered the structure of your sequence. With ALTER comand you are actually setting the increment value. Here "n" sets the increment size. If set as 1 it will increment by 1. If set as 2 will increment by 2.
    Do you guys use
    SELECT  <sequencename>.NEXTVAL FROM DUAL;to increment SEQUENCES?YES that is the correct way to increment a sequence. Use NEXTVAL to increment a sequence.
    Question *4*.
    I was trying to increment a sequence. After the ALTER statement, the sequence didn't get incremented. I had to issue a NEXTVAL call to actually get this reflected. Why is this happening?
    SQL> select * from v$version where rownum=1;
    BANNER
    Oracle Database 11g Release 11.1.0.7.0 - 64bit Production
    SQL> CREATE SEQUENCE myseq
    2    START WITH 1
    3    NOMAXVALUE;
    Sequence created.
    SQL> select myseq.nextval from dual;
    NEXTVAL
    1
    SQL> alter sequence myseq increment by 7;
    Sequence altered.
    SQL> select myseq.currval from dual;
    CURRVAL
    1
    SQL> select myseq.nextval from dual;
    NEXTVAL
    8
    SQL> select myseq.currval from dual;
    CURRVAL
    8
    Answer for the question 3 answers this one as well!!

  • Renaming "Sequence" restart after last number used?

    I'm fairly sure that when you rename files in Bridge using a sequence of numbers, it remembers what the last one used was. When you next open the dialogue box, it pre-populates the text entry box with the number following the last one used.
    This doesn't happen in Lightroom - if I want to carry on from where I left off last time then I have to shut the dialogue box again, go to the last folder of images I renamed, find the last number, go back to the original folder, re-open the rename box and then type in the last number+1! It was a real time-saver to have this feature in Bridge; it would be great to have it in LR too.

    746379 wrote:
    Hi,
    I have a sequence and i am using that in a procedure to insert records.Often the procedure throws error like primary key violated.
    When i checked the last number used by the sequence it gave me as 27331 and the currval of the sequence as 27312.
    Please advice us to rectify this.First make sure that you understand the difference between a primary key and a sequence.
    A sequence is just a number generator. Oracle guarantees that the sequence will give you a new unique number each time that you call NEXTVAL. If the sequence is cycling then it can even generate the same number again after some time but this is rarely the case.
    A primary key is a constaint on your table that requires all values in the column to be unique and not null.
    When you get an primary key violated error then you just tried to insert a value that was already there in the table.
    Some scenarios might be the reason for this.
    <li>You insert a row using the sequence. You insert a new row using the same number again without fetching it from NEXTVAL (e.g. using currval instead of nextval, or not updating a variable that holds the new ID,...)</li>
    <li>Somebody else already inserted an ID without using the sequence</li>
    <li>A variation is when you import data from another database and resetted the sequences</li>
    <li>There is some test data in your tables. The test data was inserted in a high ID range to separate it from the real data. Your sequence just reached this range.</li>

  • ALTER CURRVAL OF SEQUNCE

    I am SQL Loading a table with a view to using the it as part of a nightly update process. Further updates to the table will happen via a stored proc. When loading the table I'm using the SQL Loader sequence function to allocate a primary key. After loading the table I would like to update the sequence being used by the stored procedure so that the CURRVAL of the sequence is the same as the maximum value that has been allocated to the values in the table.
    Is there any way to do this other than to drop the sequence and recreate it, setting the min value to the maximum value allocated by the SQL Load step ?
    null

    You have 2 options here:
    I would use a before insert trigger to generate the sequence numbers as the records are loaded. You would not have a problem then.
    If you have to do it the way you described you will need to either drop/recreate the sequence or alter the sequence so that the increment is set to the difference between the sqlloader number and the next val for the sequence number, then issue a select on the sequence then reset the increment to 1.
    Hope this helps
    Ron
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Ian Dukes ([email protected]):
    I am SQL Loading a table with a view to using the it as part of a nightly update process. Further updates to the table will happen via a stored proc. When loading the table I'm using the SQL Loader sequence function to allocate a primary key. After loading the table I would like to update the sequence being used by the stored procedure so that the CURRVAL of the sequence is the same as the maximum value that has been allocated to the values in the table.
    Is there any way to do this other than to drop the sequence and recreate it, setting the min value to the maximum value allocated by the SQL Load step ?
    <HR></BLOCKQUOTE>
    null

  • Sequences problem

    Hi All,
    I have a large table consisting of 3810986 rows. We have sequences generated on the primary key column(chr_val_id).
    When we do the below query
    SELECT CHR_VAL_ID_SEQ.NEXTVAL FROM DUAL we can see that the nextval is 1615. however in the table already a record is there with the same id. i assume some other operation have loaded data without using sequence.
    Now my question is, how to reset or set CURRVAL or NEXTVAL sequence value ? so that i can point it(NEXTVAL) to the latest max(chr_val_id) ??
    i have given the table structure below for your reference..
    CREATE TABLE CHR_VAL_T
      CHR_VAL_ID         NUMBER                     NOT NULL,
      CHR_VAL_CODE       NUMBER                     NOT NULL,
      CHR_ID             NUMBER                     NOT NULL,
      NUMRC_VAL          NUMBER,
      UOM_ID             NUMBER,
      DT_VAL             DATE,
      DSCR_ONLY_FLG      VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      CMRCLY_SNSTVE_FLG  VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      CPY_ITEM_VAL_FLG   VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      INTRNL_USE_FLG     VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      EXCLUDE_FROM_HDNG  VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      AUTO_DFLT          VARCHAR2(1 CHAR)           NOT NULL,
      AVAILABLE_FROM_DT  DATE                       NOT NULL,
      AVAILABLE_TO_DT    DATE                       NOT NULL,
      CRTD_BY            VARCHAR2(50 CHAR)          NOT NULL,
      CRTD_DTTM          DATE                       NOT NULL,
      UPD_BY             VARCHAR2(50 CHAR)          NOT NULL,
      UPD_DTTM           DATE                       NOT NULL,
      LCK_NUM            NUMBER                     NOT NULL,
      DEL_IND            VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      CNSLDTD_ITEM_MOD   VARCHAR2(1 CHAR)           DEFAULT 'N'                   NOT NULL,
      MOD_TYP            VARCHAR2(1 CHAR)           DEFAULT 'S'                   NOT NULL
    ALTER TABLE CHR_VAL_T ADD (
      CONSTRAINT CHR_VAL_PK_IDX
    PRIMARY KEY
    (CHR_VAL_ID));

    Hi,
    You can temporarily alter the increment of your sequence and select the nextval in order to reach your max. Then you set by you increment to the original value.
    E.g. on 10.2.0.4 database :
    SQL> create sequence s1 increment by 1;
    Sequence created.
    SQL> select s1.nextval from dual;
    NEXTVAL
    +1+
    SQL> alter sequence s1 increment by 100;
    Sequence altered.
    SQL> select s1.nextval from dual;
    NEXTVAL
    +101+
    SQL> alter sequence s1 increment by 1;
    Sequence altered.
    SQL> select s1.nextval from dual;
    NEXTVAL
    +102+
    SQL>
    Kind regards,
    Ludovic

  • Error in the procedure while tried to increment the seq

    Hello ,
    I tried the following but giving the errors..
    Plz help me in this..
    CREATE OR REPLACE PROCEDURE Seq_inc AS
       vmaxarrec number(10);
       vseq number(10);
          select max(recid) into vmaxarrec from acc_rec;
          select SEQ_ACC_REC.currval into vseq from dual;
        BEGIN
          FOR i IN vseq .. vmaxarrec  LOOP
            select SEQ_ACC_REC.nextval  from dual;
          END LOOP;
        END ;And giving the following errors...
    LINE/COL ERROR
    4/7 PLS-00103: Encountered the symbol "SELECT" when expecting one of
    the following:
    begin function package pragma procedure subtype type use
    <an identifier> <a double-quoted delimited-identifier> form
    current cursor
    The symbol "begin" was substituted for "SELECT" to continue.
    11/9 PLS-00103: Encountered the symbol "end-of-file" when expecting
    one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    LINE/COL ERROR
    <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> << close current delete fetch lock insert
    open rollback savepoint set sql execute commit forall merge
    Thanks

    smile wrote:
    SQL> CREATE OR REPLACE PROCEDURE Seq_inc AS
    2     vmaxarrec number(10);
    3     vseq number(10);
    4       
    5      BEGIN   
    6      select max(recid) into vmaxarrec from acc_rec;
    7      select SEQ_ACC_REC.currval into vseq from dual;
    8       
    9        FOR i IN vseq .. vmaxarrec  LOOP
    10          select SEQ_ACC_REC.nextval  from dual;
    11        END LOOP;
    12   
    13      END ;
    14  /
    Warning: Procedure created with compilation errors.
    SQL> sho err
    Errors for PROCEDURE SEQ_INC:
    LINE/COL ERROR
    10/9     PLS-00428: an INTO clause is expected in this SELECT statementI tried with the above correction ..and still errorsIt looks to me like you're trying to reset the sequence number to a new starting value. In reality there's very little point in doing this, though I've come across a few test scenarios where it's good to start with the same sequence number each time.
    The logic for changing a sequence to a particular value is along the lines of:
    SQL> select test.nextval from dual;
       NEXTVAL
           125
    SQL> var v_inc number;
    SQL> var v_resetno number;
    SQL> exec :v_resetno := 50;
    PL/SQL procedure successfully completed.
    SQL> exec execute immediate 'select -(test.nextval-:x)-1 from dual' into :v_inc using :v_resetno;
    PL/SQL procedure successfully completed.
    SQL> exec execute immediate 'alter sequence test increment by '||:v_inc;
    PL/SQL procedure successfully completed.
    SQL> select test.nextval from dual;
       NEXTVAL
            49
    SQL> alter sequence test increment by 1;
    Sequence altered.
    SQL> select test.nextval from dual;
       NEXTVAL
            50
    SQL> select test.nextval from dual;
       NEXTVAL
            51
    SQL>Note: In your code you are reading the currval of the sequence before you know that you've read the nextval. That will give an error, because the currval is only known within the current session after a nextval has been obtained.
    So, as a procedure, you want something like:
    CREATE OR REPLACE PROCEDURE Seq_inc AS
      v_maxarrec number;
      v_inc      number;
      v_seq      number;
    BEGIN   
      select max(recid)+1 into v_maxarrec from acc_rec; -- get the required sequence value
      select -(seq_acc_rec.nextval-v_maxarrec)-1 into v_inc from dual; -- determine the difference
      execute immediate 'alter sequence seq_acc_rec increment by '||v_inc; -- alter the sequence
      select seq_acc_rec.nextval into v_seq from dual; -- query the sequence to reset it
      execute immediate 'alter sequence seq_acc_rec increment by 1'; -- alter the sequence to increment by 1 again
    END ;(+untested+)

  • Issue with WIP_MASSLOAD_PUB.createOneJob, R12.

    Hello,
    For one of the custom program, we have been using WIP_MASSLOAD_PUB.createOneJob to create a WIP Job. The custom program has been designed more on the same lines(almost exactly) as mentioned in http://apps2fusion.com/forums/viewtopic.php?f=3&t=422 that is, I use WIP_JOB_SCHEDULE_INTERFACE_S to generate the GROUP_ID and INTERFACE_ID
    For most of cases it works fine, but has been erroring out intermittently with an error:
    Exception in procedure main: ORA-00001: unique constraint (WIP.WIP_JOB_SCHEDULE_INTERFACE_U1) violated
    I checked the currval of the sequence WIP_JOB_SCHEDULE_INTERFACE_S (268351) and when I checked the WIP_JOB_SCHEDULE_INTERFACE Table, the max(interface_id) in the table came as 273344 -- and the records with the interface_ID above the CURRVAL of the sequence came from a standard program AutoCreate Final Assembly Orders(WICDOL)... because of this when my program inserts records from the sequence, the same interface_id value happens to be already available in the interface table causing this error.
    Now, the challenge is what does the standard program to use to generate/populate the INTERFACE_ID. Any Ideas?
    --Thanks!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I got the issue resolved.
    The Standard program uses sequence wip_interface_s for generating the interface_id.
    --Thanks!                                                                                                                                                                                                                                                           

  • SQLAssembler id-query

    Hello all,
    I have stumbled across a problem I ran across previously but I don't know how to fix the problem.
    I have an insert query in my SQLAssembler that inserts a record into our Oracle database. I have an id-query that gets the currval from a sequence for the primary key of the new record:
    <create-item>
    <sql>
    INSERT INTO WORK_QUEUE (WORK_QUEUE_ID, CREATION_DATE, DESCRIPTION) VALUES
    (#WORK_QUEUE_ID#, TO_DATE(#CREATION_DATE#, 'MM/DD/YYYY'), #DESCRIPTION#)
    </sql>
    <id-query>SELECT SUBSCRIBER_ID_SEQ.CURRVAL FROM DUAL</id-query>
    </create-item>
    where WORK_QUEUE_ID is the primary key. When this query gets called I get the following error:
    18:02:23,090 INFO  [STDOUT] lcds[DEBUG] [Service.Data.SQL] SQL Assembler jdbc exception on operation=create-item error=java.sql.SQLException: ORA-08002: sequence SUBSCRIBER_ID_SEQ.CURRVAL is not yet defined in this session
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:810)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1039)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:85 0)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1134)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3 339)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3384 )
    at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStat ement.java:342)
    at flex.data.assemblers.SQLAssembler.processIdQuery(SQLAssembler.java:1069)
    at flex.data.assemblers.SQLAssembler.createItem(SQLAssembler.java:1020)
    at flex.data.adapters.JavaAdapter.doCreateItem(JavaAdapter.java:1829)
    at flex.data.adapters.JavaAdapter.invokeAssemblerSync(JavaAdapter.java:1698)
    at flex.data.adapters.JavaAdapter.invokeBatchOperation(JavaAdapter.java:1562)
    at flex.data.adapters.JavaAdapter.invoke(JavaAdapter.java:636)
    at flex.messaging.services.MessageService.serviceMessage(MessageService.java:276)
    at flex.data.DataService.sendBatchToAdapter(DataService.java:1414)
    at flex.data.DataService.serviceTransactedMessage(DataService.java:787)
    at flex.data.DataService.serviceMessage(DataService.java:465)
    at flex.messaging.MessageBroker.routeMessageToService(MessageBroker.java:1503)
    at flex.messaging.endpoints.AbstractEndpoint.serviceMessage(AbstractEndpoint.java:898)
    at flex.messaging.endpoints.amf.MessageBrokerFilter.invoke(MessageBrokerFilter.java:121)
    at flex.messaging.endpoints.amf.LegacyFilter.invoke(LegacyFilter.java:158)
    at flex.messaging.endpoints.amf.SessionFilter.invoke(SessionFilter.java:44)
    at flex.messaging.endpoints.amf.BatchProcessFilter.invoke(BatchProcessFilter.java:67)
    at flex.messaging.endpoints.amf.SerializationFilter.invoke(SerializationFilter.java:147)
    at flex.messaging.endpoints.BaseHTTPEndpoint.service(BaseHTTPEndpoint.java:278)
    at flex.messaging.MessageBrokerServlet.service(MessageBrokerServlet.java:322)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.j ava:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.j ava:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.ja va:190)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
    at flex.messaging.security.TomcatValve.invoke(TomcatValve.java:151)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEs tablishmentValve.java:126)
    at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEst ablishmentValve.java:70)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java: 158)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.ja va:598)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)
    I found that this error happens because I am trying to use CURRVAL before using NEXTVAL according to the Oracle site. But I don't understand why this is happening when it is. If I perform an action that uses a similar insert and id-query, I do not get that error and the new row is added correctly.
    Does anyone know why this is happening? Has anyone run into this problem before?

    For LCDS documentation is not very clear. Try to edit newDependent added before adding to the collection. If you want to edit later, then take it from the collection, after finnish, commit changes.
    However it is not usual to add a object to collection and then edit it immediately. Not very logical in terms of how the application is built.

  • GetGeneratedKeys() functionality in 10G

    Hello,
    The getGeneratedKeys() function on Statement or PreparedStatement class does not seems to be supported? Also not when using Oracle 10g JDBC driver (version 10.1.0.2.0) when connecting to 9I database (9.2.0.5)? When trying it I get SQLException: Unsupported feature.
    Is the getGeneratedKeys() function supported when connecting to a 10g database?
    I'm migrating from another database platform (Informix), and found the use of serial keys handy. What I have done now on Oracle is created a sequence and "before insert" trigger which automatically inserts new value for key field. I had hoped that the getGeneratedKeys() function should have worked...
    In case it is not supported, what is the advised way to retrieve new key value?
    Thanks!
    Kristof Adriaenssens

    Thanks for the tip Avi.
    In the meanwhile I already found that getGeneratedKeys() is indeed not supported: http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.htm#02_04
    I however found a solution which requires some more code then I hoped for, but it works. Here an example:
    PreparedStatement statement=con.prepareStatement("INSERT INTO autoinc_test (NAME) VALUES (?)");
    statement.setString(1,"Test");
    statement.executeUpdate();
    Statement getAutoGenValueStatment=con.createStatement();
    ResultSet rs=getAutoGenValueStatment.executeQuery("select autoinc_test_seq.currval from dual");
    if (rs.next())
    System.out.println("Serial value: "+rs.getInt(1));
    rs.close();
    getAutoGenValueStatement.close();
    statement.close();
    The retrieval of currval on a sequence returns correct value as it is session dependent. So even when another session inserts a record in same table after our session inserted a record and before retrieving the currval, we are sure that we will get correct value.

  • Reliable detect number of occurences (table lock needed or ?)

    Hi all,
    I got an issue with detecting duplicate messages. Database clients process files and messages and create a hash value that is passed on to the database. The database should return the number of occurences of this hash value in the last (e.g) 14 days.
    create table HashHistory ( ID NUMBER,
    MESSAGEHASH VARCHAR2 (20),
    TS TIMESTAMP);
    create sequence SomeSequence;
    insert into HashHistory values (SomeSequence.nextval,'first hash', systimestamp);
    insert into HashHistory values (SomeSequence.nextval,'second hash', systimestamp);
    create or replace procedure DuplDetection  (p_HashIn varchar2,
                                         p_occurences OUT number) AS
    l_timestamp timestamp default systimestamp;                          
    begin
      -- possible exclusive table lock here... lock table HashHistory in exclusive mode;
      insert into HashHistory values (SomeSequence.nextval, p_HashIn, l_timestamp);
      select count (1)
      into p_occurences
      FROM HashHistory
      where MESSAGEHASH = p_HashIn
      and   TS < l_timestamp
      and   TS > l_timestamp-14;
      commit; --to release the table lock if applicable
    end;When this procedure is called by two different machines at the same time with the same new hash value ('third hash'). One session should return 0 while the other should return 1 as number of occurences.... With default Oracle behaviour using row level locks, and executing them in parallel both sessions will not be able to see the others sessions hash values, and both will return 0 occurences. Is an exclusive table lock my only option to enforce this behaviour or can I trust Oracle to handle this correctly?
    I expect 10^6 hashes each day and possible up to 10 or 20 clients running at the same time generating and checking these hash values. What are the changes of both sessions returning the same value without an exclusive table lock (as in this example)? What other parameters would you consider?
    I am on Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi

    Nicosa wrote:
    Hi,
    Wouldn'that work if you do it as follows ?insert into HashHistory values (SomeSequence.nextval, p_hashIn,...);
    commit;
    select count (1)
    into p_occurences
    FROM HashHistory
    where MESSAGEHASH = p_HashIn
    and   TS > l_timestamp-14
    and ID!=SomeSequence.currval;The second session should see that some others existing hash were inserted, and hence an be warned.No, it wouldn't work. Some kind of synchronization is required.
    In multi-threaded environment you cannot predict the order of execution of this program.
    Let say we have a server with only one processor and 3 users (sessions) connected to that server.
    Three users (let say U1, U2 and U3) call this procedure to insert the same hash. The procedure has 3 operations: insert, commit, select,
    and assume theoretically that these 3 operation are atomic (each takes only one processor cycle - in reality each of these operations can consume thousands of cycles).
    Server can execute these calls in this order:
    U1-insert (sequence + 1)
    U1-commit
    U1-select (returns 0)
    U2-insert (sequence + 1)
    U2-commit
    U2-select (returns 1)
    U3-insert (sequence + 1)
    U3-commit
    U3-select (returns 2)
    - in this scenario results will be OK.
    But the order might be:
    U1-insert (sequence + 1)
    U1-commit
    - here server decides to switch to another process/thread
    U2-insert (sequence + 1)
    U2-commit
    - server switches to proccess 3
    U3-insert (sequence + 1)
    U3-commit
    - server switches back to U2
    U2-Select (user 2 sees record commited by U1 and U3 and returns 2)
    - server switches to U3
    U3-Select (user 1 sees record commited by U1 and U2 and returns 2)
    - server switches to U1
    U1 - Select (this also returns 2)
    - results are 2,2,2, but should be 0,1,2
    If 20 users cal this procedure at the same moment with the same hash value, it is even possible that each user gets 19 as the final result,
    but proper results should be 0, 1, 2, 3 .... 19 ;)
    Without some kind of synchronization this a lottery.
    There is also another trap with the sequence - consider this example:
    Session 1
    SQL> create sequence abc;
    Sequence created.
    SQL> select abc.nextval from dual connect by level <=5;
       NEXTVAL
          1
          2
          3
          4
          5
    SQL> select abc.currval from dual;
       CURRVAL
          5Session 2
    SQL> select abc.nextval from dual;
       NEXTVAL
          6
    SQL> select abc.nextval from dual connect by level <=5;
       NEXTVAL
          7
          8
          9
         10
         11
    SQL> select abc.currval from dual;
       CURRVAL
         11Back to session 1
    SQL> select abc.currval from dual;
       CURRVAL
          5What happens in this scenario:
    - user 1 does insert (select nextval from the sequence)
    - user 2,3,4,5,6 ..... 100 call the procedure just 3 microseconds after U1 and do insert (increase the sequence)
    - user 1 retrieve currval from the sequence ?

Maybe you are looking for

  • Thinkpad W520/T61p Bad experience

    I am sharing this story in retrospect of the events.  I posted this on a popular tech blog on a thread discussing bad experience with different computer companies and I decided why not post it here as well.  I am still grieving over my dead T61p as i

  • IBOOK to TV

    I can't get the iBook to display to a TV. I have the adapter (single RCA or S-Video) but can't make it work. Help!

  • Cat3560 and AAA Authenticatin

    Hello guys, I tried to configure the CAT3560 Switch with IAS Windows 2003 AD authentication without success. Is it possible at all?? If so, do I have to use Standard RADIUS in the Win 2003 IAS or Vendor specific type. I was looking in Internet and go

  • Bonjour not displaying messages

    We use Bonjour in my office to communicate only within the office. Sometimes (may 20% of the time) I'll send a message, and it won't appear on the other persons computer. We have desktops and laptops, and some may have different OS, but all are 10.4

  • Strange Text in Blackberry Messenger

    Anyone else had this..Started getting strange characters in the text when using Blackberry Messenger. Totally random...sometimes it will be fine and then it will start randomly changing characters....hard to show here as I can't type them..but as if