How to generate unique values while initializing values

I am initializing values in my pl/sql program and want to use a sequence to set my unique ids but it errors out. Below is what I use.
ie. table_id := table_seq.nextval;
How can I use my sequence to initialize values or is this possible?

The method suggested by user605919 will work. However, you don't need to initialize a variable like this. It is better and more performant to do it like the third example below:
SQL> create table mytable
  2  ( id number(6)
  3  , description varchar2(30)
  4  )
  5  /
Tabel is aangemaakt.
SQL> create sequence table_seq start with 1 increment by 1
  2  /
Reeks is aangemaakt.
SQL> declare
  2    table_id mytable.id%type := table_seq.nextval;
  3  begin
  4    insert into mytable
  5    ( id
  6    , description
  7    )
  8    values
  9    ( table_id
10    , 'Some description'
11    );
12  end;
13  /
  table_id mytable.id%type := table_seq.nextval;
FOUT in regel 2:
.ORA-06550: line 2, column 41:
PLS-00357: Table,View Or Sequence reference 'TABLE_SEQ.NEXTVAL' not allowed in this context
ORA-06550: line 2, column 12:
PL/SQL: Item ignored
ORA-06550: line 9, column 5:
PLS-00320: the declaration of the type of this expression is incomplete or malformed
ORA-06550: line 9, column 5:
PL/SQL: ORA-00904: "TABLE_ID": invalid identifier
ORA-06550: line 4, column 3:
PL/SQL: SQL Statement ignored
SQL> declare
  2    table_id mytable.id%type;
  3  begin
  4    select table_seq.nextval
  5      into table_id
  6      from dual
  7    ;
  8    insert into mytable
  9    ( id
10    , description
11    )
12    values
13    ( table_id
14    , 'Some description'
15    );
16  end;
17  /
PL/SQL-procedure is geslaagd.
SQL> begin
  2    insert into mytable
  3    ( id
  4    , description
  5    )
  6    values
  7    ( table_seq.nextval
  8    , 'Some description'
  9    );
10  end;
11  /
PL/SQL-procedure is geslaagd.And if you need the id value for some code after the insert, you use the RETURNING clause.
Regards,
Rob.

Similar Messages

  • How to generate unique filenames??

    i need to be able to generate unique files from a servlet..
    my initial instinct was to use the seesion id as part of the filename, however as this file will be embedded in the responding html, this is not safe, as the user will only have to look at the html source to view a session id value.
    i am now considering to use the date/time of the creation of a session as the unique identifier for the file, however this will not work if two sessions can be created at the same time.
    my question thefore is if no two sessions can have the same date and time?
    if not.. can anyone give me an idea as how to produce unique filenames?

    If you are actually creating a file, why not usethe
    java.io.File.createTempFile() method?how does that help with prducing a unique value to use
    as the name of a file?
    with that method i still need to supply the filename
    as one of its arguments!
    No you don't. You provide a prefix and suffix and it fills in the middle with something guaranteed to be unique, in the directory you specify. Here is the javadoc:
    createTempFile
    public static File createTempFile(String prefix,
    String suffix,
    File directory)
    throws IOException
    Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
    1. The file denoted by the returned abstract pathname did not exist before this method was invoked, and
    2. Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
    This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
    The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as "hjb" or "mail". The suffix argument may be null, in which case the suffix ".tmp" will be used.
    To create the new file, the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform. If the prefix is too long then it will be truncated, but its first three characters will always be preserved. If the suffix is too long then it too will be truncated, but if it begins with a period character ('.') then the period and the first three characters following it will always be preserved. Once these adjustments have been made the name of the new file will be generated by concatenating the prefix, five or more internally-generated characters, and the suffix.
    If the directory argument is null then the system-dependent default temporary-file directory will be used. The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.
    Parameters:
    prefix - The prefix string to be used in generating the file's name; must be at least three characters long
    suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used
    directory - The directory in which the file is to be created, or null if the default temporary-file directory is to be used
    Returns:
    An abstract pathname denoting a newly-created empty file
    Throws:
    IllegalArgumentException - If the prefix argument contains fewer than three characters
    IOException - If a file could not be created
    SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created
    Since:
    1.2

  • How to generate unique numbers

    hi all,
    I want to generate unique numbers always starting from 1 using a single sql query and I dont want to use a sequence and i dont think rownum will be helpful for generating unique numbers in all cases . how to do this ?
    thanks & regards,
    kumar.

    If two users get the MAX from temp, they would be updating with the same value for two different rows.If TEMP is a genuine temporary table, this is not an issue, because the data in a temporary table is only visible within a session.
    The big problem with this approach is the mutating table one: we cannot issue the requisite select statement from a BEFORE INSERT trigger. So this solution is only going to work with a view and an INSTEAD OF INSERT trigger.
    Another, more workable, solution is to use a code control table. This can be (should be) another temporary table, with one row holding one column - next value for TEMP.ID. Normally we would rule out such a solution because it serializes access to the inserted table, but as this is only on a per session basis, it doesn't matter.
    CREATE OR REPLACE TRIGGER tmp_bir BEFORE INSERT ON temp1 FOR EACH ROW
    DECLARE
      ln NUMBER;
    BEGIN
      SELECT nvl(code1.next_id,1) INTO ln
      FROM code1;
      :NEW.id := ln;
      UPDATE code1
      SET    next_id := ln+1;
    END;Beware: coded freehand, so may need debugging.
    Cheers, APC

  • Actual value and initial value showing same text

    Hello,
      I am working with recruiting data. I have created and infoset that has Publications doing a left outer join with Requisitions. This is because the query is trying to list all publications for a requisition and the requisition information should still show on the query even if there is no publication. I am getting the correct records BUT when there is no publication, the initial or 'not assigned' value prints for all fields EXCEPT for publication status. Publication status is a NUMC field and it has a key 0 with the text of 'draft'. Unfortunately when there is no record the initial value is in the key but 'draft' is in the text. I would like the text to say 'not assigned'. I tried to put a space record in the master data text table but since the field is NUMC, it said it already existed. I tried to put a 0 record in the master data and it said it already existed. So as far as the table is concerned space and zero are the same. And due to the query results I'm guessing the initial value is a space or zero. Can anyone tell me how to get 'Not Assigned' to print if there is no publication but 'draft' to print if the key value for publication status is a zero?
    Thanks,
    Diane

    There was a glitch in our network or yours. I didn't mean to post twice.
    Diane

  • How to generate username automatically while user creation in OIM.

    Hi all,
    Could you please send me steps for how to generate user name automatically by using adapter while creating the user in OIM.

    Follow this link:
    [http://download.oracle.com/docs/cd/B32479_01/doc.903/b32457/creadp.htm|http://download.oracle.com/docs/cd/B32479_01/doc.903/b32457/creadp.htm]
    It will help you to make each adapter which you want but for this you'll have to create entity adapter.

  • How to generate controls dynamically based on value stored in database using mvc4?

    In my database, i have a field called control_ids corresponding to  text box, dropdownlist, radiobuttonlist etc. My goal is to
    create controls dynamically based on value of control_id-field in table. Anybody please help me how to create the controls dynamically in MVC 4 for this scenario.

    In your view you could do something like that:
    foreach (var field in Model.FormStruture.fields)
    <div class="editor-label">
    <label for="@field.Name">@field.Descricao</label>
    </div>
    <div class="editor-field">
    <input class="text-box single-line" id="@field.Name" name="@field.Name" type="text" value="@field.Valor" data-rules-required="@field.Mandatory.ToString().ToLower()" data-rule-number="@field.Tipo.Equals(SiB.OCR.Documentos.Modelo.TipofieldDocumento.Numerico).ToString().ToLower()" title="@field.Descricao" />
    </div>
    if (!String.IsNullOrEmpty(field.Format))
    @:<script type="text/javascript">$("[email protected]").mask("@field.Format");</script>

  • How to generate pulse during changing boolean value?

    I need to generate short pulse during changing boolean value from 0 to 1. This pulse is needed to reset counter. 
    I was trying with Event Structure with Value Change but I think that I did something wrong.
    Maybe sambody can give me some tips to do it in other way?
    Thank you in advance.
    Regards
    Solved!
    Go to Solution.

    Rogal wrote:
    I need to generate short pulse during changing boolean value from 0 to 1. This pulse is needed to reset counter. 
    I was trying with Event Structure with Value Change but I think that I did something wrong.
    Maybe sambody can give me some tips to do it in other way?
    Thank you in advance.
    Regards
    We assumed you wanted a pulse when a front panel button (boolean) was clicked.
    I am still not sure just what it is you want.
    Do you want a single pulse when x is greater than 4?
    You don't need an event structure for that.
    Omar

  • How to generate a text file with values from internal table

    hi,
    can anybody help me out to get the values from different internal table written into a text file.
    regs,
    raja

    used gui_download,ws_download,cl_gui_file_save.
    data: ld_filename type string ;
    ld_filename = 'c:\demo.txt'.
    DATA: begin of it_datatab occurs 0,
    row(500) type c,
    end of it_datatab.
    HII
    call function 'GUI_DOWNLOAD'
    exporting
    filename = ld_filename
    filetype = 'ASC'
    tables
    data_tab = it_datatab[]
    exceptions
    file_open_error = 1
    file_write_error = 2
    others = 3.
    gui_download

  • How to generate unique IDs for a metadata field

    Hi,
    We have a requirement to generate a unique ID for a metadata field. Does anybody know how this can be achieved? Ideally I would want to have a database sequence and specify the metadata field to get value from this database sequence, similar to how Content ID is generated.
    Any help is appreciated. Thank you in advance.
    Regards,
    Tim

    Look into the Counters table. You should be able to create a component install filter to add in your field to the Counters table.
    You could then create some Java code to fetch the next value from the Counters database for your field (and increment the value).
    Jonathan
    http://redstonecontentsolutions.com
    http://corecontentonly.com

  • How to Generate Unique Cache Keys?

    I'm trying to improve the performance of my ColdFusion 10 application by making better use of caching.  I have a particular DAO/Gateway CFC that queries a particular database.  I added query caching to the query in this CFC and it made a huge difference.
    Since this database is outside my control for edits/updates, I need to be able to initiate flushing of the cached queries for this database only.  I don't believe the built-in ColdFusion ehcache query cache allows for granular control of flushing - in CF Administrator you pretty much can only flush the entire cache.
    So I figured the only solution was to create my own cache region that would be associated with just this database, and manually cache the queries into that region.  Then I can flush just that region without impacting any other cached queries.
    So here's my difficulty:  I believe that Internally, ColdFusion caches queries using a hash of the generated SQL.  I'm thinking I'll store my queries in cache with a key that hashes the input parameters.  Would the built-in Hash() function be the appropriate mechanism to create cache keys that are unique for each parameter combination?  Does it matter what algorithm I use with Hash()?
    Thanks,
    -Carl V.

    Sorry, didn't see your original question! You might be better asking this on StackOverflow, as there's more people who have more experience with CF keeping an eye on the questions there.
    What I can offer is that MD5 hashes are not guaranteed unique for different input strings. It's unlikely to happen, but it can happen. I think - but am not sure - more "thorough" hashing algorithms might be more likely to have a higher degree of uniqueness.
    That said, the general approach is how these things are generally done.  And it's very very unlikely that you'll ever come to use a combination of elements contributing to the key that will generate a hash that you've already used for something else.
    Adam

  • How to generate unique PKIDs to add a new translation

    We need to add a new translation to the table commonXLAExtensionCache. However in the documentation it states:
    -Verify that the pkid that is being inserted is unique per insert. It must start with 1058.
    How can we generate a unique pkid, is there a database command.
    For this example, we are adding a new translation for a custom FlexSync report are using.

    MSSQL DB
    select '1058' + upper(newid());
    Oracle DB
    select ('1058' || newid) from dual;

  • How to Generate   Unique Serial No in Oracle 6i report

    Hi
    I want to generate a unique serial no for every row ,
    how can i achieve this result.
    thanx in advance

    You can also use the analytical function ROW_NUMBER in your query
    SELECT ...
               ROW_NUMBER() OVER (ORDER BY YOURORDERBY) RN
      FROM TABLE
    ORDER BY RN;

  • How to generate Unique Seq Id in BPEL

    Hi All,
    How can we generate a unique seq Id in BPEL.
    One way is to use "*orcl:generate-guid()*" .
    Are there any other ways by which we can generate the unique seq id. please send me some sample piece of code if any for example.
    Regards
    Narendra
    Mail to: [email protected]

    Probably not best practice, but I created a sequence in one of my Oracle DBs to call and get a unique ID. You could do something similar with a call to a SQL DB. If you don't care if it is a number or not you could use the Generate GUID function within BPEL.
    --S                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to generate unique random numbers

    Hi All,
    I am wondering whether there is already a random library or built-in function available in Java to produce some random numbers between certain ranges that are not repetitive. Let's look at a common examples as follows:
    Random diceRoller = new Random();
    for (int i = 0; i < 10; i++) {
      int roll = diceRoller.nextInt(6) + 1;
      System.out.println(roll);
    }My understanding from this approach is that it allows the same number to be repeated over and over again. However, I would like to find out how to continue generating random numbers from remaining ones that haven't been generated earlier.
    Using the above example to illustrate my intention:
    1st random number generated - possibility of 1 - 6 showed up. Say 5 is picked.
    2nd random number generated - possibility of 1, 2, 3, 4, 6 only. Say 2 is picked.
    3rd random number generated - possibility of 1, 3, 4, 6 available. Say 1 is picked.
    4th random number generated - possibility of 3, 4, 6 left. Say 6 is picked.
    5th random number generated - possibility of 3, 4 remains. Say 4 is picked.
    Any assistance would be much appreciated.
    Many thanks,
    Jack

    htran_888 wrote:
    Hi All,
    I am wondering whether there is already a random library or built-in function available in Java to produce some random numbers between certain ranges that are not repetitive. Let's look at a common examples as follows:
    Random diceRoller = new Random();
    for (int i = 0; i < 10; i++) {
    int roll = diceRoller.nextInt(6) + 1;
    System.out.println(roll);
    }My understanding from this approach is that it allows the same number to be repeated over and over again. However, I would like to find out how to continue generating random numbers from remaining ones that haven't been generated earlier.
    Using the above example to illustrate my intention:
    1st random number generated - possibility of 1 - 6 showed up. Say 5 is picked.
    2nd random number generated - possibility of 1, 2, 3, 4, 6 only. Say 2 is picked.
    3rd random number generated - possibility of 1, 3, 4, 6 available. Say 1 is picked.
    4th random number generated - possibility of 3, 4, 6 left. Say 6 is picked.
    5th random number generated - possibility of 3, 4 remains. Say 4 is picked.
    Any assistance would be much appreciated.If it is your school assignment then you have the answer above (List & the lists length).
    (You might want to look at Collections)

  • How to generate unique document number ?

    Hi All,
    We need to generate Document Number where there should be any gap, so that we cannot use sequence. For example : Invoice Number.
    one possible approach like : Select MAX(InvoiceNumber)+1 from invoice, what if that table has millions of rows, is this reliable enough ?
    How to avoid two user do the same query at same time that lead to dupplicate number ?
    Anybody has done it this way in production? or any other approach ?
    Thank you for your info,
    xtanto

    I strongly second Justin's strong suggestion about re-considering the requirement.
    Be aware that for any of the schemes suggested to have a chance of working, all access to the table must be through stored procedures that use a SELECT FOR UPDATE on the counter table. No user in the database can have insert privileges on the document table except the owner. The owner's password should be kept in a locked safe and be unknown to anyone. If for some reason the owner needs access to the database, then remove the password from the safe, do what needs to be done, then get some guy off the street to set a new password, write it down and lock it in the safe again.
    If you really need a gap-free number, it needsto be another column, separate from the PK. Use a sequence to generate the pk gaps and all, then create a procedure that runs periodically to update the gap free column. Soemthing like:
    SQL> CREATE PROCEDURE fix_gap_free AS
      2     l_v NUMBER;
      3     TYPE id_tbl IS TABLE OF number INDEX BY BINARY_INTEGER;
      4     l_ids  id_tbl;
      5     l_id2s id_tbl;
      6  BEGIN
      7     SELECT MAX(NVL(id2,0)) INTO l_v FROM t;
      8     SELECT id, ROW_NUMBER() OVER (ORDER BY id)
      9     BULK COLLECT INTO l_ids, l_id2s
    10     FROM t
    11     WHERE id2 IS NULL;
    12
    13     FORALL i IN 1 .. l_ids.COUNT
    14        UPDATE t
    15        SET id2 = l_id2s(i) + l_v
    16        WHERE id = l_ids(i);
    17     COMMIT;
    18  END;
    19  /
    Procedure created.
    SQL> SELECT * FROM t;
            ID        ID2
             1
             2
             5
             7So, id2 is going to be the gap-free column.
    SQL> exec fix_gap_free;
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t;
            ID        ID2
             1          1
             2          2
             5          3
             7          4So first pass is fine. Now lets add a few rows, so the table now looks like:
    SQL> SELECT * FROM t;
            ID        ID2
             1          1
             2          2
             5          3
             7          4
             8
             9
            25and generate more gap free number:
    SQL> exec fix_gap_free;
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t;
            ID        ID2
             1          1
             2          2
             5          3
             7          4
             8          5
             9          6
            25          7If there may be deletions in the table, and you need to maintain the gap free nature, then just skip the WHERE id2 IS NULL predicate.
    John

Maybe you are looking for

  • Best practice for adding application to $env:Path in PowerShell?

    I'm trying to figure out the best way to add a program to PS's path. When I look at $env:Path, I see tons of different entries pointing to various programs on the system that seem to have been added by their installers. This would suggest that I coul

  • Video/audio Stuttering on Macbook 13

    Hi All I have a mid 2007 Macbook 13 running OS X Lion 10.7.4.  all up to date.  Initially I had 4G's of ram ( I know it only reads 3 ) now I have it running on only 2. Problem is video/audio stuttering when running movies. mostly netflix and or conne

  • Mod video files

    Hi, I have iMovie 4 and OS 10.3.9. 1) Can I somehow work with mod files (which my new video cam produces) in iMovie 4? 2) If not, which other program besides iMovie could I use, best without having to update to another OS or iMovie? 3) Do I have to c

  • Paid for Premium account through PayPal,.but didn't upgrade my account, what??

    Hi,I've just tried to upgrade my Spotify account to Premium through PayPal, it has worked flawlessly before. But today it didn't, my creditcard were charged by Spotify through PayPal and corresponding amount were reserved on my MasterCard Debit. Plea

  • Mailto: in Flash CS3

    Dear Sirs, I use Flash CS3 for making home pages. For movie clips, that are going be used for email, I use e. g. the following code: astamail_mc.addEventListener(MouseEvent.CLICK,astadown); function astadown(event:MouseEvent):void var request4:URLReq