How to get the auto increment integer primary key value of a new record

I have a DB table that has a auto increment integer primary key, if I insert a new record into it by SQL statement "INSERT INTO...", how can I get the integer primary key value of that newly created record?

Well maybe someone knows a better method, but one workaround would be to add a dummy field to your table. When a new record is inserted this dummy field will be null. Then you can select your record with SELECT keyField FROM yourTable WHERE dummyField IS NULL. Once you've got the key number, you then update the record with a non-null value in the dummyField. Bit of a bodge, but it should work...
Another alternative is, instead of using an Autonumbered key field, you could assign your own number by getting the MAX value of the existing keys (with SELECT MAX(keyField) FROM yourTable) and using that number + 1 for your new key. Might be a problem if you have lots of records and frequent deletions though.

Similar Messages

  • Auto Increment of primary key value in jdeveloper.

    hi all,
    i have one table with one primary key.
    i want to increment that primary key when ever i go for CreateInsert or create operation in JSF page.
    i have tried with db sequence value type, but i was not able to achieve my condition. in DB Sequence i got error like cannot convert java.class.string to java.class.dbsequence.
    can any one suggest me in this to achieve my condition.
    regards,
    M vijayalakshmi.

    hi all,
    from this i found the simple method to achive the auto increment of primary key.
    http://www.techartifact.com/blogs/2012/10/adding-number-for-primary-key-in-oracle-adf-using-groovy-by-sequence.html#ixzz2EeU9CWo6
    in this am facing an one small issue.
    intial value of the primary key is 1.
    for this value i have entered the row of data.
    again i have clicked on the create button.
    then the value of the primary key has increased to 2.
    for this value i didnt entered the row of data to databse.
    just i closed the browser.
    if i run the run page again, the value of primary key is 3.
    my requirment is i shd get the value of primary key is "2".
    the increment shd happen the maxi value present in the primary key of the table.
    can any one help me in this how to achive this.
    thanks in advance.
    regards,
    M vijayalakshmi.

  • How to get the current node element by its value?

    e.g,:
    wdContext.current<b>Deal</b>Element().setAttributeValue("<i>deal_id</i>","<i>aaaaaaa</i>");
    above code can get the result i wanna.
    but now i wanna in terms of its node'name to  set attribute vaue of itself. in other words,i have no idea about how to get the current node element by its name"<b>Deal</b>".

    Hi Wing,
    The answer is there in your question itself.
    wdContext.currentDealElement()
    will give you the current node element by its name"Deal" or you could use
    wdContext.nodeDeal().getCurrentElement()
    or you could use
    wdContext.nodeDeal().getElementAt(wdContext.nodeDeal().getLeadSelection())
    Regards,
    Sudeep

  • How to get the inheritance level for an atribute value

    hi,
    i have to get the inheritance level for an attribute value for a given user in Org.struc.

    Hi,
    Check out table T77OMATTUS for inheritance level for an attributes
    Regards,
    Neelima

  • EJB3: One-to-one relationships and auto-generation of primary key values...

    Dear Forum,
    I'm relatively new to JEE, and while I've so far enjoyed the convenience of EJB3 for most things, it seems that I have a corner case that can not be handled by the entity manager.
    First, here's a quick mockup of my entities:
        Gallery
                |
                -- [1] -------[1] ----> Author
                |
                -- [1] -------[M] ---> Photo
                                                  |
                                                  -- [1] ------ [1] -> PhotoImage
                                                                                     |
                                                                                     -- [1] ------ [1] -> IPTCData
                                                                                     |
                                                                                     -- [1] ------ [1] -> EXIFDataI also have a remote, stateless session bean that does nothing more than persist()/merge()/remove() and locate (through find() and a few custom queries) my Gallery and Photo instances.
    Now, the abridged version of my problem is this: when I persist a Photo, it naturally gets its primary key generated (I used @Id and @GeneratedValue). However, for some reason none of the other dependent entities inherit Photo's primary key value. In my client, I create a new Gallery locally and then persist it. I then create new Photo, PhotoImage, IPTCData and EXIFData instances. I add the IPTCData and EXIFData instances to PhotoImage (there are PhotoImage methods for adding those); then I add the PhotoImage instance to Photo (again, Photo has a setter for adding a PhotoImage). Then, I persist the Photo.
    --- Aside: ------------
    I've set up my relationships using annotations like @OneToMany (Gallery references a Collection of Photos), and @OneToOne (Photo's primary key references PhotoImage's primary key; PhotoImage's primary key references the primary keys of IPTCData and EXIFData). I've also added @JoinColumn annotations where necessary.
    Finally, I get the Gallery instance's Photo collection (public Collection<Photo> getPhotos()), I add the Photo to the collection, and I add the Photo collection BACK to the Gallery (public void setPhotos(Collection<Photo>)).
    At this point, the Gallery should have all of my entities contained inside of itself. However, when I persist the Gallery at this point, all of the entities show up in the database, but none of the primary keys get inherited. Photo's primary key gets generated automatically, of course, but the rest have zero (0) as their PK values. I had wanted, for example, IPTCData to get the value of Photo.id.
    I had assumed that the entity manager would persist everything for me provided that I told it, through my annotations, about which entities relate to which. Does persistence only work in the direction of retrieval? That is, does the entity manager only do its thing when fetching (versus setting) data when there is more than 1 object in the graph? I can't believe that it can't, otherwise we'd all be ditching it and going back to straight SQL to do our work.
    Thus, I HAVE to be doing something wrong, or else omitting to do something right.
    I've made other incarnations of the above setup, and none of them have worked perfectly. I've even set up foreign key constraints in the database, but I had my share of unresolvable problems there, too.
    So I guess my big question with all of this is: when you have a deeply nested graph of objects, can the entity manager figure everything out and persist all of the objects correctly and with the right values? If not, boo. If so, how does one accomplish this?
    I know that I could persist each and every entity separately in my client code, but I wanted to have a natural-looking way of piecing all of my entities together. More specifically, I could persist IPTCData explicitly; however, I want to be able to add everything to a Photo and only persist the Photo itself, with the idea that all of the objects and sub-objects would be persisted automagically.
    Is this possible? Or have I bought into a pipe dream with the guarantee of the proverbial magic bullet?
    Thanks to everyone in advance for his/her input.
    Regards,
    Michael

    Daniel,
    Late last night I found the solution to my problem. And you're right, it had everything to do with which side is wired to which. I got confused about which side to consider the "owning" side, since one can look at it from the perspective of the database or the application.
    Interestingly, the first 2 lines of your example code match my client code almost verbatim: First, I create a new Gallery (or else I get an existing one). I then create a new Photo and then add it to the Gallery's collection using add(). I then persist the Gallery. My session bean internally calls EntityManager.merge(gallery). How it differs from your example, though, is in the fact that, on an application level, a Photo has no knowledge whatsoever of a Gallery. Which is to say that my Photo class does not have a 'getGallery()' method. Somehow, Hibernate is able to figure it all out and still update Photo's 'parentIdRef' column in the database. My logs show that Hibernate issues a SQL UPDATE on the Photo after both a Gallery and a Photo have been created. It sets the Photo's 'parentIdRef' column to the primary key value of the owning Gallery.
    Getting back to the matter, my problem was not with being able to map a Photo to a Gallery; rather, I was unable to add a PhotoImage to a Photo and have the relationship get correctly mapped in the database. The relationship between a Photo and a Gallery is many-to-one: there can be many Photo objects inside of a Gallery. In the database, a Photo row contains a 'parentIdRef' column whose value is that of a Gallery's primary key. I used @OneToMany on the Gallery, since a Gallery is, from an application perspective, the "owning" side, even though it's only the Photo that knows who it's referring to since only IT contains the 'parentIdRef' column in the database.
    I tried setting up the relationship between a PhotoImage and a Photo in the same manner, with the PhotoImage having a 'parentIdRef' column and referring to a Photo's primary key. I had annotated the Photo's getPhotoImage() method with @OneToOne, along with an appropriate @JoinColumn.
    It was THIS part that I had backwards. With a @OneToMany relationship, the child refers back to the parent --- it can be no other way. However, with a @OneToOne relationship, the owner refers to the child.
    So, to make a long story short, all I had to do was create extra database columns for Photo. Those columns refer to the primary keys of PhotoImage, EXIFData and IPTCData. Concretely, for example, Photo.photoImageIdRef references PhotoImage.id. And so on and so forth.
    The only negative side-effect of this is that my database-level foreign key constraints are now broken, since Hibernate wants to persist PhotoImage, EXIFData and IPTCData before it persists Photo.
    I have to investigate more deeply the 'cascade=...' option of the @OneToOne annotation in order to find out it relates, if at all, to a database-level cascade.
    Anyway, thanks for the reply. It seems that you had a very good idea about what my problem was. I would have posted the fact that I had resolved the problem last night, except that it was too late and I was heading to bed. If you still want the Duke points, let me know. I don't currently know the rules about if, when and to whom I should issue points in cases like these when I've already solved the problem.
    Regards,
    Michael

  • HOW TO  GET COUNT IN OF COMPOSITE PRIMARY KEYS USING ECLIPSELINK

    Hi all,
    We are currently migrating our application form oracle 10g to 11 g and hence migrating from toplink to eclipselink.
    we are unable to fire the count query and getting the following exception ...
    Error Code: 909
    Call: SELECT COUNT() FROM T_USER_MESSAGE t0, T_USER t2, T_MESSAGE_RECIPIENT t1 WHERE ((((t2.PERSISTENT_ID = ?) AND (t2.SITE_CODE = ?)) AND (t1.DELETED_BY_RECIPIENT = ?)) AND (((t2.PERSISTENT_ID = t1.RECIPIENT_ID) AND (t2.SITE_CODE = t1.RECIPIENT_SITE)) AND ((t0.PERSISTENT_ID = t1.MESSAGE_ID) AND (t0.SITE_CODE = t1.MESSAGE_SITE))))
         bind => [13398610, 1, F]
    please advise .
    we suspect that this could be because of the composite primary key in one of the tables .
    any pointers to specify how count(*) could be used in this scenario would be of great help ..
    Thanks in advance

    What is the query being used, include the JPQL/expression code.
    What is the error message (I assume this is a database error?).
    What version are you using, can you try the latest EclipseLink 2.1 release.
    James : http://www.eclipselink.org

  • How to get the organized files back when you move to a new computer

    How to get your file folder organization back when you move to a new computer?

    Your PSE8 is using the default, new empty catalog that's created when PSE is installed.
    In Windows, search your entire computer for this file:
    catalog.pse8db
    The largest one that's found will be your old catalog.  If your computer people didn't restore that catalog file (and its entire directory), ask them where the heck it is.
    Ken

  • How to populate field on page with Primary Key value from previous page

    I am trying to create a patient tracking system for a group of doctors. There is an add patient form based on the Patient table (which has Patient_Id as its primary key) which branches to a pre-operative assessment form. I would like to populate the pre-op assessment Patient_Id field with the Patient_Id generated by the Add Patient page during processing, which comes from the Patient_seq sequence. How can I do this? I have tried using a computation on the Pre-Op Assessment form, but no matter what I put in, the field remains blank.

    Hi,
    If I understand you correctly, once patient record is created you branching to next page (pre-operative assessment form). First create a static hidden item in patient form *:PX_PATIENT_ID_COPY*.
    Create an On submit after computation and validation process in patient form to get the inserted patient_id from patient table. Here is the code -
    SELECT patient_id into :PX_PATIENT_ID_COPY from patient_table where rownum=1
    order by patient_id descI would not use the sequence to get the current value because if the inserted record been deleted from your patient table, sequence current value would not be valid to find that record in patient table.
    Basically when the record been inserted, the process get the value and put into the hidden item.
    Pass the value from the hidden item to the next page by setting them in page branch. Under the Action section in the page branch, Set this items field type - *:PX_PATIENT_ID* (next page item for patient_id). Type *&PX_PATIENT_ID_COPY.* in the with these values field. Make sure you include dot(.) after *&PX_PATIENT_ID_COPY*.
    Give it a try now. Hope it would helps.
    Regards,
    Tajuddin
    Blog: http://aspblog.whitepagesbd.com
    web: http://tajuddin.whitepagesbd.com

  • How do I let user enter a primary key value on a form

    I'm creating my first APEX application. I have a simple table called HOSTS with 2 columns HOSTNAME and IP_ADDRESS. HOSTNAME is the primary key for the table. HOSTNAME is a perfectly acceptable primary key and I don’t wish to create an additional column to be populated by a sequence.
    What are my options for creating a form on the table without using "Existing trigger", "Custom PL/SQL function" or "Existing Sequence" to populate the primary key column, i.e. HOSTNAME, so that the user can enter a value for the primary key?
    Any assistance greatly appreciated.
    Gavin

    The debate about natural keys versus surrogate keys
    will no doubt continue with advocates for both sides.
    However there is also a difference between
    'making your life easier' for APEX development and
    'making your life more difficult' by having to
    analyse, implement and deploy a surrogate key only
    approach to an existing database which employs both
    natural keys and surrogate keys.
    hould we be forced to change the database design
    because a development tool does not cater for natural
    primary keys?The application development product is TRYING to save you from shooting yourself in the foot. The idea is to separate the primary key from being accessed by the user or ANY carbon based unit.. The key is mainly used by the system to join and lookup data rows, not for people to change whenever they decide that the key is WRONG.
    Think about this, if you use Last Name as a key in your system (a bad idea to begin with since this is NOT a unique id when you have two Smiths). When a person needs to change this because Jimmy Smith is NOT the only Smith working for Acme Toys, you have to cascade that change through all the child tables related to the main person table.
    If instead you use a system generated key, no change will be required since the key has NO relation to the data other than it represents a pointer to that row of data.
    Works for me, since I do not want to write all the supporting code when APEX builds it for you...
    Thank you,
    Tony Miller
    UTMB/EHN

  • Problem with a primary key when creating a new record in Forms

    My table has a field - MDD_KEY - that is a primary key. It is updated from a sequence with a before-insert database trigger. I know this works properly as the primary key was accurately populated when I inserted 1433 records.
    In Forms 6, I have a form based on that table. I have set the mdd_key as a hidden field because I assume it will be entered by the before-insert trigger. However, when I enter data into the table, and then try to save it, I get a FRM-40202: Field must be entered. - followed by - FRM-40222: Disabled item MDD_KEY failed validation.
    If I set DATA Required to no, when I try to save I get an FRM-40600: Record has already been inserted - but no such record exists in the database. I know this record is unique and does NOT exist because I deliberately made it up.
    In the property palatte, the attributes of the field are:
    DATA Data Type Number
    Required Yes
    DATABASE Database Item Yes
    Primary Key Yes
    Query Only No
    Query Allowed Yes
    Query Length 0
    Insert Allowed Yes
    Update Allowed Yes
    Update Only if Null No
    Lock Record No
    I assume that my problem is that with a new record, the form wants to see the MDD_KEY populated before it saves - but that isn't going to happen until the before insert trigger fires in the database. I assume I have to populate that field within forms, but how do I do that without messing up the database trigger/sequence? I will have to load more data directly into the database - so I need the database trigger in place.
    I have not used primary keys before so I am more than a little bit confused about how and when it should be populated when a new record is created in Forms.
    Any help would be appreciated as I cannot enter new data into my form (works well with existing data).
    Thanks
    Glenn

    hi
    if u have any problem using seq then try that statemetn ur block level in ur form
    PRE-INSERT trigger
    select nvl(max(nvl(srno,0)),0)+1 into :srno from tablename;
    Rizwan

  • How to get the wireless router to work when i change to new modem and internet connection

    I already set up my wireless router in my macbook but then moved to a new house and basically have a new internet connection. My internet connection is fine when i connect the ethernet cable form the modem to my macbook. But when i plugged in the wireless router, my computer sees it but will not connect to the internet. I lost my installation CD and i tried to re-install using the dowloaded installation but it goes into error saying i can't re-install if i don't change back to default.. anyway, maybe the solution is simple but it eludes me so please help!
    In summary:
    1. same macbook
    2. same wireless router
    3. same internet provider but new connection and modem (since i moved to a different house)
    how do i get my wireless router to work? thanks!!!

    Who is your Internet Service Provider(ISP)?
    If you have a cable connection then follow this link and if you have a DSL connection then follow this link to configure your router.

  • How to get the current GMT time in java

    Hi,
    How to get the current GMT time in java
    Thanks

    System.getCurrentTimeMillis() or new Date().
    [url http://www.javaworld.com/jw-12-2000/jw-1229-dates.html]Calculating Java dates: Take the time to learn how to create and use dates
    [url http://www.javaalmanac.com/egs/java.text/FormatDate.html]Formatting a Date Using a Custom Format

  • ?Trigger to return primary key value after insert"

    Ok, so I'm a newbie to oracle. I was hoping someone could tell
    me how I can get the value of a field after insertion. I
    created a sequence and a trigger to autoincrement the primary
    key. I figured out that select @@Identity does not work. So
    I'm trying to figure out how to return the primary key value of
    just inserted record.
    Any help or suggestions would be really appreciated.
    thanks matt

    I have 3 tables - master, detail and collector.
    when a record is inserted into the collector table - I want to fire a trigger and insert the value of "collector.a_test", "collector.b_test" into "master.test" and "detail.test" respectively.
    I want to create an after/insert trigger on the collector table to accomplish this. I tried to implement the example listed in previous message (see below) *** BUT **** I get a PLS-00103 error - "Encountered the symbol "A_ID" when expecting one of the following: :=. ( @ %;
    Note: master, detail and collector have before insert trigger/sequence that assigns their PK values.
    master has 2 columns - a_id (number PK), a_test (varchar2(255))
    detail has 3 columns - b_id (number PK), b_test (varchar2(255)), aa_id (number FK)
    collector has 3 columns - c_id (number PK), a_test (varchar2(255)), b_test (varchar2(255))
    as in;
    create or replace trigger wf.c_a_b_insert
    after insert on wf.collector
    referencing old as old new as new
    for each row
    declare
    aa_id master.a_id%type;
    begin
    insert into master (a_test) values(:new.a_test);
    returning a_id into aa_id;
    /* now insert into detail and get the FK value from aa_id */
    end;
    What am I doing wrong and how can I fix this?
    Thanks much!
    Bill G...

  • Apple Mail - how to get the first word in a sentence to auto-capitalize

    How to get the first word in a sentence to auto-capitalize
    Anwar

    something to look forward to then, because we get used not to use our shift button any more, since iPhone and iPad do it for us. entourage and other ms stuff do it. pages does it too now (put it on in the auto-correct in preferences). bizarre however some loose the capitalization when you copy the text. pages to stickies or mail does not. that's good !

  • How to get the value of String in integer type

    how to get the value of String in integer

    {color:#0000ff}http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#valueOf(java.lang.String){color}

Maybe you are looking for

  • BW Sales Budget retraction to SAP R/3

    Hi , I need some help in Data Retraction from BW to SAP 6.0. I am able to to get data from BW 7.0 to SAP 6.0, the data is a SALES BUDGET.  I am running the Transaction code KELR. The Problem tha i am facing is with the Charactreristics  "PRCTR"  Prof

  • I have $84 store balance but need to change registered country (I moved - foreign credit card)...

    Can I spend that and won't have a problem later when I change my country, with apps and everything? I read your 'purchased'  won't show your stuff anymore, but you can still search individually and re-download free, sounds like some chaos comes with

  • Help me decide which Ipod...Please!!

    I'm trying to decide between the Nano or the 5Th Generation with video. One question, I notice that there are very few movies on Itunes...in fact I don't really see any...just the TV shows and a few shorts from Pizar. (and of course the movie trailer

  • Regarding siebel adapter

    hi   i am supposed to send a request from webdynpro using webservice,   the back end is siebel where i am supposed to get the output as flatfile. can anyone help on this with a example regards Ramakrishna

  • Where do you put colour profiles ???

    Hi I hope you can help me we have our own icc colour profile that i want to synchronise in adobe bridge to use on the whole suite. Can you tell me where i have to put the profile for it to appear in the list when i go to creative suite color settings