Auto Increment Primary Keys

I am trying to migrate from SQL Server. I want to setup tables which generate sequencial Primary keys on adding records to the table. I have a VB application which is using ADO with an ODBC connection. How does one use the Oracle Enterprise Console Manager to set a Primary Key to increment on the adding of new records automatically. In SQL Server one just needs to set an Identity, Identity Seed and Identitiy Increment. In Access there is a datatype called AutoNumber. Help would be greatly appreciated. I am using 9i with a standalone Enterprise Console Manager. Thanks in Advance.

You first have to create a sequence and then the trigger below:
Instead of data in single quotes(') you must specify the appropriate for your db names
CREATE OR REPLACE TRIGGER 'Schema'.'trigger_name' BEFORE
INSERT ON 'table_name'
FOR EACH ROW
BEGIN
SELECT 'sequence_name'.nextval into :new.'column_name' from dual;
END
;

Similar Messages

  • CMP with auto-increment primary key.Please help

    Hi all,
    I new with EJB technology so please bear with me.
    Env: 2k Server, SQL 2k Server
    Sun One(Forte EE) to develop and deploy CMP
    I got the servlet to load the data from CMP's business mehods
    is fine. Calling the findPrimaryKey is OK too. Even when I try to insert the row into DB is OK. At this time I make key PK is int AND NOT
    AUTO INCREMENT everything is OK. In the ejbCreate method
    I called setPK, setName ...It's fine.
    The problem comes when I try to make the PK(still int) to be auto-increment field.In ejbCreate not call setPK because of in SunOne IDE, under the J2EE RI tab of EJB Module property, the Auto generate SQL I set to false so that I can
    modify the SQL statement under SQL Deployment.createRow not taking the PK. I thought that will do it but it doesnot like it at all (I got Exception with transaction rollback)I just want to insert a single row with ID and name that's all.
    Then I changed the SQL statment take PK and changed the Auto Generate SQL to True and in ejbCreate the PK as one of the args and called setPK this time with null object. It doesn't like neither.(Exception Cannot set the primary key with null. That is reasonable.)
    I thought using EJB fast and clean technique would help developer to develop application with easiness.
    So I realy stuck with this, I wonder ejb 2.0 support for auto increment at all because I would like to take advantage of the auto increment feature of the DB without writing the PrimaryKeySequence generator at all.
    Am I missing something with this? May be just config thing to tell
    that my PK is auto-increment field so that when the ejbCreate called it knows not taking the PK or even not asking to call setPK in ejbCreate.
    Any help would appreciated.

    Check out this thread, there's a bunch of good info:
    http://www.theserverside.com/patterns/thread.jsp?thread_id=4976

  • How can I use a mySQL database schema with numeric auto increment primary key instead of GUID?

    Hello!
    I'm using the TestStand "MySQL Insert (NI)" database schema with GUID as primary key. So everything works fine.
    But I prever using numeric values as primary key, because the database is in conjunction with another database which uses numeric values as primary key.
    Is this possible?
    Has anyone an idea how I can modify the "Generic Recordset (NI)" for use with MySQL?
    Thanks!
    Configuration:
    Microsoft Windows XP
    TestStand 3.1
    MySQL 4.1.12a
    MySQL ODBC 3.51 Driver
    Brosig

    Adam -
    The TestStand Database Logging feature does not allow you to run a separate SQL command after executing the command for a statement(table), so I do not think that you can use an auto incrementing column for the tables. There is just no way to get it back in a generic way. One option that I tried is something similar to the Oracle schema where you call a store procedure to return a sequence ID for each record that you want to add.
    So you would have to create the following sequence table in MySQL:
    CREATE TABLE sequence (id INT NOT NULL);
    INSERT INTO sequence VALUES (0);
    Then create a stored procedure as shown below that will increment the sequence value and return it in a recordset:
    CREATE PROCEDURE `getseqid`()
    BEGIN
            UPDATE sequence SET id=LAST_INSERT_ID(id+1);
            SELECT LAST_INSERT_ID();
    END
    Then update the MySQL tables to use INT primary and foreign key values, so the TestStand MySQL SQL file to create all tables would have text like this:
    CREATE TABLE UUT_RESULT
     ID    INT  PRIMARY KEY,
    ~
    CREATE TABLE STEP_RESULT
     ID    INT  PRIMARY KEY,
     UUT_RESULT   INT  NOT NULL,
    ~
    Then update the schema primary and foreign key columns in the TestStand Database Options dialog box to be INT to match the table. For the primary key columns, you will have to set the Primary Key Type to "Get Value from Recordset" and set the Primary Key Command Text to "call getseqid()". This will call the stored procedure to determine the next value to use as the ID value.
    Hope this helps...
    Scott Richardson
    National Instruments

  • How to have an auto increment primary key in HDBDD

    Hello,
    Using a HDBDD file I am creating a table in which I need a primary key(recordId) which is auto generated by the DB.
    What would be the way to do this?
    My hdbdd file:
    namespace sap.mobile.data;
            @Schema : 'SAP_TEST'
    context Sample {
    @Catalog.tableType : #COLUMN
      entity Details {
      text : LargeString;
      level : String(10);
      timestamp : UTCTimestamp;
      recordId : ?

    Such syntax for calculated columns isn't supported yet by CDS/HDBDD. The work around people would use today is to use a Sequence in any logic that does an insert into this table.

  • CMP with Auto-increment Primary Key problem

    I'm trying to set a column as IDENTITY in PointBase and have the app server utilize this in the CMP beans. I followed the instructions from the tutorial:
    - In the deployment descriptor, the primary key class is defined as a java.lang.Object. The primary key field is not specified.
    - In the home interface, the argument of the findByPrimaryKey method must be java.lang.Object.
    - In the entity bean class, the return type of the ejbCreate method must be a java.lang.Object.
    Below is (a fragment of) my deployment descriptor:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
    <ejb-jar>
    <display-name>CMPModule</display-name>
    <enterprise-beans>
    <entity>
    <display-name>DocState</display-name>
    <ejb-name>DocState</ejb-name>
    <home>com.sun.itstar.j2ee.projectdocmgt.ejb.DocStateHome</home>
    <remote>com.sun.itstar.j2ee.projectdocmgt.ejb.DocState</remote>
    <local-home>com.sun.itstar.j2ee.projectdocmgt.ejb.LocalDocStateHome</local-home>
    <local>com.sun.itstar.j2ee.projectdocmgt.ejb.LocalDocState</local>
    <ejb-class>com.sun.itstar.j2ee.projectdocmgt.ejb.DocStateBean</ejb-class>
    <persistence-type>Container</persistence-type>
    <prim-key-class>java.lang.Object</prim-key-class>
    <reentrant>False</reentrant>
    <abstract-schema-name>DocState</abstract-schema-name>
    <cmp-field>
    <field-name>name</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>description</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>color</field-name>
    </cmp-field>
    </entity>
    In the admin-serv/logs directory I get the follow message (bad place for the logs, took me a while to find where it was putting it!):
    [24/Sep/2002:16:33:57] WARNING ( 4165): Validation error in bean DocumentType: Warning: All primary key columns in primary table DOCUMENT_TYPE of the bean corresponding to the generated class com.sun.itstar.j2ee.projectdocmgt.ejb.DocumentTypeBean_387898907_JDOState must be mapped to key fields.
    Map the following primary key columns to key fields: DOCUMENT_TYPE.ID. If you already have fields mapped to these columns, verify that they are key fields.

    Great! This worked. Here are some clear steps:
    1. delete the field from the CMP
    2. delete any business methods that you might have for the field
    3. go to the properties of the bean, find the primary key property. Set the property to Unkown Primey Key Class (java.lang.Object)
    Now there is a bigger problem. CMR fields. In ejbPostCreate() the bean gets its own pk and looks up other related beans. Now that I have removed the accessor to the pk field (and the pk field from the bean), how do I lookup the relationships?
    I need some method that I can call from within ejbPostCreate() that will return the primary key...
    I tried adding the field back in but not as the primary key. That generated an exception that said you cannot do that. If the field is the pk it must be marked as the pk.
    Any ideas?

  • How to impliment a auto increamenting  primary key feature in ADF ??

    How to implement an auto incrementing primary key feature in ADF ( With out using database Triggers)
    Edited by: Dinil Mithra on Apr 24, 2009 2:28 AM
    Edited by: Dinil Mithra on Apr 24, 2009 2:59 AM

    Dinil,
    Create a sequence in the database.
    Read section 4.11.5 of the Fusion Developer's Guide - which has sample code to get the next sequence value from Java without a database trigger.
    John

  • Auto increment of key in TopLink (by Anizio)

    Hi friends!
    Sameone know how I do auto increment of key when I insert an object on the data base with topLink?
    I have used to Jdeveloper 1013
    Thank

    Hi Doug
    I tryed but happened a error.
    I do this: in my descriptor, I enable the options "Use sequencing", then, this is equals:
    Name: SEQ_ID_TITULAR
    Table: DEVPORTAL.CAD_TITULAR
    Fiels: CAD_TITULAR.TIT_ID
    In the name I put the sequence name created in the database, but an error called "invalid number" happen.
    Can you help me ?

  • How to "auto" generate "Primary Key" in custom table?

    Hi Folks,
    Requirement:
    I need a function module or program that can create automatically a primary key.
    Scenario:
    I have a program that creates an entries and save it to a custom table at the same time, but a primary key should always be generated respective to the entries saved.
    Example:
    Material(MATNR) 4001001, Plant(WERKS) XX01, ID[Primary Key-auto generated]
    (I'm thinking of a similar concept/logic on how a unique IDOC number is being generated or how SAP standard creates a unique entry)
    I try to look for any SAP FM that can generate a PK, but there's no luck.
    Thanks.
    Regards,
    Jun

    Hi Keshu and All,
    The links are helpful, however:
    #1. I don't have authorization to create a new object in transaction SNRO, but the way I see the objects in SNRO is just for defining the length(number of characters) for the ranges that will be use if I'm not mistaken.
    #2. FM NUMBER_GET_NEXT - yes it can populate incremental unique entries but it's only occurring at runtime ?? So when the program get terminated it's not being saved nowhere.
    So after if I use FM NUMBER_GET_NEXT, I always have to look for all the last primary key in my custom table, then target it as my starting point for creating a new PK.  I think this will give a performance issue, any comments?
    For better visualization, I have scenario:
    1.  (ZQ_CREATE_PK) Create unique incremental PK for material, batch, so on..
    2.  Append line/entries to ZQ_TABLE
    3.  Repeat #1 and #2
    4.  User exits the program
    5.  Back to 1 --> At this point, I need to get the "LATEST" PK then start this as a starting point again to generate PK and append it to ZQ_TABLE
    I'm assuming that SAP has other SAP FMs related in creating this scenario.   Similar to IDOC # creation..
    Thanks.

  • JDO Auto Generate Primary Key

    Hi
    I am working with JDO.
    I want to auto generate the primary key value that should increment for each entry into database.
    How can i do it, please guide me.
    Any link or doc will be appreciated.
    Regards
    Osman

    There is only one answer to "how I do this" questions: read the manual.
    Any link or doc will be appreciated.Google. Seriously dude, a forum is not your personal information service - go make some effort yourself. Come back when you have an actual problem that you need help with.

  • Retrieving auto inc primary key from entity bean (MySQL DB)

    Hello,
    I searched the forum intensively, but did not find an answer for the following problem.
    I've set up an MySQL database "Location" with two fields (ID, Description), ID is my primary key and I've added the AUTO_INCREMENT flag to this field. This works fine, i can add a row in the table with my entity bean "Location" from my session bean :
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    and even when I ask this location back from the DB, there is no problem :
    Location l = em.find(Location.class,1);
    return l.getDescription();
    The rows in the table increment nicely. The problem however is, that you don't allways know the ID. So I would like to do the following from my session bean:
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    int id = l.getId();
    the getID method allways returns a null object. The row is added in the DB, but the auto incremented ID is not returned to the entity bean!
    I know I could solve this by generating the ID's myself, but one of the strengths of autoincrement should be not to have to do this, no?
    If anyone has a clue how to solve this issue, I would very much appreciate it !
    Michiel
    Edited by: Michiel82 on Dec 6, 2007 6:01 AM

    No reactions so far ... this is a work-around for the issue :
    I've created an additional table sequence with two fields: gen_key and gen_value. Then, in my Location entity bean I can add the following:
    @TableGenerator(
    name="locationGen",
    table="sequence",
    pkColumnName="gen_key",
    valueColumnName="gen_value",
    pkColumnValue="location",
    allocationSize=1
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE,generator="locationGen")
    @Column(name = "id", nullable=false)
    private Short id;
    This generates the primary key in the bussiness logic, but I would like to get the autogenerated key from my MySQL database (see previous post). Is this perhaps not supported by EJB3.0?
    Michiel

  • Creating entity beans with auto numbered primary key

    I have two entity bean with a CMR between them. I am successfully creating the first one but when I try and create the child entity bean I get a NullPointerException.
    Now I think this is because the gernerated code tries to get the primary key of the created entity bean and this is not set as it is set using a auto number in the database (An oracle sequence and trigger).
    Is there anyway i can get round this problem?
    Thanks in advance,
    Adrian

    This is the auto generated code:
         public dmd.sync.ejbs.entity.AppliancePackInfoLocal create_Local(dmd.sync.dataobjects.dto.AppliancePackInfoDTO appliancePackInfoDTO, dmd.sync.ejbs.entity.AmppLocal amppLocal) throws javax.ejb.CreateException, java.rmi.RemoteException {
              BeanO beanO = null;
              dmd.sync.ejbs.entity.AppliancePackInfoLocal result = null;
              boolean createFailed = false;
              boolean preCreateFlag = false;
              try {
                   beanO = super.createBeanO();
                   dmd.sync.ejbs.entity.AppliancePackInfoBean bean = (dmd.sync.ejbs.entity.AppliancePackInfoBean) beanO.getEnterpriseBean();
                   preCreateFlag = super.preEjbCreate(beanO);
                   bean.ejbCreate(appliancePackInfoDTO, amppLocal);
                   Object ejsKey = keyFromBean(bean);
                   result = (dmd.sync.ejbs.entity.AppliancePackInfoLocal) super.postCreate_Local(beanO, ejsKey, true);
                   bean.ejbPostCreate(appliancePackInfoDTO, amppLocal);
                   super.afterPostCreate(beanO, ejsKey);
    It must be falling over on the last line as it calls the ejbPostCreate fine.

  • Auto-increment primary

    I am new to oracle db
    Does anybody tell me how to make my primary key as a DBSequence type and automate increment one by one?
    below is my table structure
    CREATE TABLE CUSTOMER(
    CUSTOMER_ID NUMBER(10) NOT NULL,
    CUSTOMER_NUMBER NUMBER(20) NOT NULL,
    CUSTOMER_NAME VARCHAR2(50) NOT NULL,
    CONSTRAINT PK_CUSTOMER PRIMARY KEY (CUSTOMER_ID)
    What I want is every time I insert new row into table
    the CUSTOMER_ID will be automatically increased one by one.
    thanks a lot

    From http://www.ddbcinc.com/askddbc/topic.asp?TOPIC_ID=239
    CREATE TABLE ab (
      ab_id  NUMBER PRIMARY KEY,
      bf_id  VARCHAR2(8),
      fs_id  VARCHAR2(8)
    CREATE SEQUENCE ab_seq
      START WITH 1
      INCREMENT BY 1
      CACHE 100;
    CREATE OR REPLACE TRIGGER ab_preinsert
    BEFORE INSERT ON ab
    FOR EACH ROW
    BEGIN
      SELECT ab_seq.nextval
        INTO :new.ab_id
        FROM dual;
    END;Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Master-detail with auto-generated primary key(master)

    Hello,
    I have the following master-detail setup:
    Master - block A primary key is: codeA
    Detail - block B
    codeA is genrated only at commit time and is obtained from a sequence.
    User needs to add detail records. This is easy to do since he has to click on the insert icon on the toolbar. At commit time, use commit_form.
    Prob: the requirements as asked by the client is to add a button (which we will label INSERT DETAIL). When the user click on the button, it opens a window where he can enter the detail info then click on save. This should bring him back to the master-detail form and the record in the detail block is inserted.
    What is the problem here ? since the detail block has the foreign key tied to the master primary key, the window-form (with the call_form) that we opened for the detail entry won't be able to save since at this point we still have not assigned a value for the primary key (and hence a value for the foreign key).
    Possible Suggestions:
    -Use a temp database table to hold the detail record from the second form and use it to transfer values to the detail record in the master-detail
    -Use a global record group
    -We can't use parameter list to pass back these values.
    So my question is:
    What would be the most efficient way to have an insert button on the detail block that would allow the user to have a pop up where he can insert his values and then be brought back to the master-detail.
    Thanks.

    Hello again,
    May be I was not clear enough.
    Scenario 1: We use the master-detail form as is with the default oolbar. In this case, the user can insert the detail records one by one without needing the primary-foreign key value since this is handled by default.
    Once we save the form (commit_form), I use the pre-insert trigger to get the master block primary key generated from the sequence and since the detail block key is copied from this value, both are saved correctly and it is the end of the story.
    Scenario 2: As explained in the initial post, the user will populate the detail records one by one by clicking on the -INSERT DETAIL- button and hence has a window where he can insert the detail info and then be brought back to the master-detail form every time he enters a new detail record.
    The problem here is that I can't generate the primary key for the master block since the client has the following requirement:
    The user can always change his mind and not complete, meaning save the form, his process
    As such, the key should be generated in the last step before Commit.

  • Auto populating application identity primary key?

    I'm sure this has been asked before but I couldn't find anything by many
    searches.
    I have some classes with int or long as their primary key. I prefer using
    application identity so the application can have direct access to the
    primary key.
    I would like to have the primary key automatically populated by Kodo from
    a sequence such that I can do:
    MyObject test = new MyObject();
    pm.makePersistent(test);
    assertTrue(test.getId() > 0);
    Is this possible in Kodo? I haven't been able to find it. I know I can do
    it with datastore identity but I would really like to avoid that.
    Thank you,
    Joel Shellman

    Hi Joel,
    before you may consider to use auto-incremented appid PK's let me tell
    some things from my own experience.
    If you have auto-incremented primary key fields you have consider that
    their values will be finally set when you commit the transaction.
    So if you access the pk fields during a transaction their values will be
    NOT set until you call explicitly KodoPersistenceManager.flush() or commit
    the transaction.
    If you use applications identity and if you have a compound PK's which one
    its fields presents a foreign key from a relation, you have to consider
    this behavior and maybe run into problems.
    I had many problems with it and finally build a wrapper around the
    sequence generator instance from KodoHelper.getSequenceHelper ().
    Greetings,
    Matthias
    Stephen Kim wrote:
    Joel, there is not, unless you are using auto-incrementing primary keys.
    You can do it in application code by calling
    KodoHelper.getSequenceHelper (). Note that you should not have this in
    an empty constructor as it may interfere with integration with JDO's
    registration system.
    Joel Shellman wrote:
    I'm sure this has been asked before but I couldn't find anything by many
    searches.
    I have some classes with int or long as their primary key. I prefer using
    application identity so the application can have direct access to the
    primary key.
    I would like to have the primary key automatically populated by Kodo from
    a sequence such that I can do:
    MyObject test = new MyObject();
    pm.makePersistent(test);
    assertTrue(test.getId() > 0);
    Is this possible in Kodo? I haven't been able to find it. I know I can do
    it with datastore identity but I would really like to avoid that.
    Thank you,
    Joel Shellman
    Steve Kim
    [email protected]
    SolarMetric Inc.
    http://www.solarmetric.com

  • How to create a primary key

    Hello - New to Oracle and was wondering what is a good way to create an auto-incrementing primary key for a table. I have done this so far:
    Created a new sequence cst_swq begin with 1 increment by 1.
    CREATE OR REPLACE TRIGGER CST_TRIG
    BEFORE INSERT
    ON COOKIE_SALES
    REFERENCING NEW AS NEW
    FOR EACH ROW
    BEGIN
    SELECT CST_SEQ.nextval INTO NEW.SALE_ID FROM dual;
    This does not really work for me. Help with the code or a better idea to create primary key is much appreciated, thank you.

    adi26 wrote:
    This does not really work for me. What does that mean?
    In which way does this approch not meet your requirements?
    BTW: after 200+ posts you should have learned how to use tags...
    bye
    TPD                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • Move a big file from a mac system to a windows 8 laptop usb usb flash drive

    Hello i am using a 32 gb flash drive to copy a 10gb file from mac os x to my flash drive. Then i want to insert that flash drive to my windows 8 pc and store it there. I cant use a network connection to transfer files because i dont have a ethernet c

  • Making text in a PDF darker???

    Is the only way to make text in a PDF darker to use Document-->OCR Text Recognition-->Recognize Text Using OCR and then use the ClearScan PDF Output Style?

  • Why am I unable to use anything when I open Firefox?

    I've been having this problem since I installed the beta. When I open up Firefox, the screen immediately freezes. Nothing is able to function: the url bar, my home page, the menu bar, NOTHING. I've even tried reinstalling the beta twice (beta 4.9 and

  • How do I get iTunes to store my Movies/tv on an External Drive?

    Well, my Laptop's running out of space & I thought it best if I began shifting my movies & tv over to my external drive (seeing as they're bigger files than music & podcasts). I've read elsewhere that it is possible, however they were only instructio

  • How do I eliminate an autofill in an e-mail address?

    When I type in one of my e-mail addresses into the "To:" box in Mail, it autofills with "Holidays in the United States".  This is my Gmail address and I at one time had Calendar linked to this Gmail account, so I'm guessing that's where it came from.