Returning autogenerated primary key after insertion

Hi
I am inserting a row into the database using simple jdbc statement. The primary key for that row is autogenerated by the database.
Is there any way to get the primary key and return it to the user?

PreparedStatement ps = con.preparedStatement("INSERT INTO Table (title, name) VALUES ("test", "name")", PreparedStatement.RETURN_GENERATED_KEYS);
ps.executrUpdate();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
primaryKey = rs.getInt(1);
}

Similar Messages

  • Help me to return the primary key after insert the row

    Hi
    I am using JDBC, with oracle database. i have welformed normalization tables .i am inserting parent table with dynamic sequence number as primary key .after inserting i need inserted row primary key .how to get the inserted row primary key with out using select statement
    please help me
    Thanks in advance
    Edited by: 849614 on Apr 4, 2011 5:41 AM
    Edited by: 849614 on Apr 4, 2011 5:54 AM

    Hello
    If I undestand you, I think you should do this:
    Connection conexion = dataSource.getConnection();
    int idCenter=-1;
    String query = "Begin Insert into CENTER (NAME_CENTER) values (?) returning ID_CENTER into ?; end";
    callableStatement = conexion.prepareCall(query.toString());     
         callableStatement.setString(1, "Center name");               
         callableStatement.registerOutParameter(2, java.sql.Types.INTEGER);
              callableStatement.executeUpdate();
              idCenter=callableStatement.getInt(2);
    This way, you have in idCenter the primary key of the line that has just been inserted.
    Edited by: cris on 05-abr-2011 5:28

  • Insert record and return the primary key

    Okay, I need to insert a record into a MSSQL database and return the primary key of that record. Im using the following code which is obviously wrong as I'm getting either 'NULL' or 'com.microsoft.jdbc.base.BaseResultSet@1d520c4' returned depending on the ways I've tried. The primary key is an int value called clientID which is incremented by one each time a new record is added.
    // set the prepared statement
                String sql="INSERT INTO Client(username, country, clientIP, browser, os) VALUES(?,?,?,?,?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, inUserName);
                pstmt.setString(2, inCountry);
                pstmt.setString(3, inClientIP);
                pstmt.setString(4, inBrowser);
                pstmt.setString(5, inOS);
                // Insert the row
                pstmt.executeUpdate();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SCOPE_IDENTITY()");
                System.out.println("Result "+rs);The primary key value is needed so that it can be used as a foregin key in another table. Am I going about this the correct way? Any help, pointers or code fixing would be appreciated.....

    Yes. I tried this way but I only ever get the answer
    of 0 when i print our the result! Not really sure
    whats happening.That's because you don't print a ResultSet like that. In order to get the key out, you have to do this:
    int key = 0;
    while (rs.next())
        key = rs.getInt(1);What were you thinking with your code?
    You might want to do this in a transaction. If the INSERT fails, you'll want to roll back.
    The "select @@identity" is correct for M$ Access, SQL Server, and Sybase. I believe it's also correct for MySQL, but I'm not 100% certain of that.
    %

  • Problem with inserting into table that has autogenerated primary key

    hi
    i am working on EJB3.
    i am trying to insert object into table.Primary key of table will be generated automatically.I tried following statement for insertion,
    em.persistent(customerObj);
    but it throw following exception,
    javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): customer.CustomerInfo
         at org.jboss.ejb3.tx.Ejb3TxPolicy.handleExceptionInOurTx(Ejb3TxPolicy.java:69)
         at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:83)
         at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:191)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:76)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:62)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:77)
         at org.jboss.ejb3.security.Ejb3AuthenticationInterceptor.invoke(Ejb3AuthenticationInterceptor.java:102)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:47)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
         at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:211)
         at org.jboss.ejb3.stateless.Stateles
    can anyone tell me is there any other way to acheive the same.
    i thought of doing using insert query,but i am not sure about the syntax to be used.
    could anyone help me ?
    thanks in advance...

    That's why you should use PreparedStatement instead of Statement. Its setString() method will escape that value for you properly when you bind it.
    %

  • How do I autogen a value for primary key on inserts

    I'm running 4.0. I am writing an app that maintains distributed database inventory information. All of my tables have surrogate numeric primary keys. I have created several report/form combinations. From the report, I can choose to create a new instance of an object; Server for instance. When I click the "Add Server >" button, the Detail page opens for me to create the new entry. On this page, I need to have the Server_ID autogenerated. I'm thinking something as simple as "Select (max(server_id)+1) from Server" should do. In fact, it looks like it is going to work because the field gets populated correctly. But, when I click the "Create" button on this page I get an error that says the Server_ID is null. Seems like the generated value isn't making it to the INSERT statement.
    On the Page Definition, I have Server_ID set as Display Only and in the Source section for the attribute I have "Only when current value in session state is null" selected and "SQL Query (return single value)" selected with "Select (max(server_id)+1) from Server" in the "Source value or expresssion" field.

    Hi Ken,
    From your description it appears you want the new server ID to be assigned and show on the page prior to collecting the rest of the information, rather than assigning it upon saving the new row. What you're doing will get the next available ID, but what happens if two or more people are entering new servers at once? There's a good chance they'll all get the same next ID.
    Tony's suggestion will ensure the uniqueness of the server ID because it'll get assigned upon saving the row, rather than on display of the page where a user could leave the screen sitting there while others "take" that next ID. You can return the value that the trigger assigns for display - if you're using an Automatic Row Processing process, see the Return Key into Item setting.
    If you're going to stick with your approach and just need to know how to make sure that field is included in the INSERT, you need to create a computation on that item and move your "select max..." there, and then for the server ID item change the Source Used to "Always...", Source Type to Database Column, and specify the column name from the table in the Source Value. The reason is hasn't been working is that field isn't currently mapped to the table column.
    Hope this helps,
    John

  • Violation of Primary Key after a successful Update of BP

    When I've updated a BP via VB.net is there something I should do with the BP object after I've done an update?
    I can't seem to do consecative updates or I get the following error:
    Violation of PRIMARY KEY constraint 'CRD1_PRIMARY'. Cannot insert duplicate key in object 'CRD1'
    This is the code I use for updating:
    For i = 0 To oBusinessPartner.Addresses.Count - 1
                oBusinessPartner.Addresses.SetCurrentLine(i)
                If (oBusinessPartner.Addresses.AddressType = SAPbobsCOM.BoAddressType.bo_ShipTo) Then
                    '** Check only SHIP TO Addresses
                    If (oBusinessPartner.Addresses.AddressName = cbSAPShipTo.SelectedItem) Then
                        '** Address User wishes to update
                        oBusinessPartner.Addresses.AddressType = SAPbobsCOM.BoAddressType.bo_ShipTo
                        oBusinessPartner.Addresses.AddressName = lSAPAddressItems(iIndex).Company
                        oBusinessPartner.Addresses.Street = lSAPAddressItems(iIndex).Address1
                        oBusinessPartner.Addresses.City = lSAPAddressItems(iIndex).City
                        oBusinessPartner.Addresses.ZipCode = lSAPAddressItems(iIndex).Postal
                        oBusinessPartner.Addresses.State = lSAPAddressItems(iIndex).Prov
                        oBusinessPartner.Addresses.Country = lSAPAddressItems(iIndex).Country
                    End If
                End If
            Next
            lRetCode = oBusinessPartner.Update()
    I check to make sure the address i want to up date is a ShipTo address, then I check to make sure that the item I am editing matches the one in the BPObject's CurrentLine.
    Then I just change the values and .Update() it
    After I've done this though, if I try to update another ShipTo address in the same BP, it comes up with that error.
    Should I kill the BP object and reinitialize it?

    Hi Tyler,
    I totally understand what you wanna do.
    The clauses which you use is trying to add a new address in the name of existing address.
    You have to do 'setcurrentline' clause, I guess.
    But now, you don't know 'what is the ShipTo line'.
    Then, I think you'd better use some simple, easy but timely expensive way.
    1. Count the records in CRD1 under conditions of the cardcode.
    -> then you can get the number of addresses of the business partner.
    2. use a loop (while, for.. doesn't matter.)
    -> Now you can use setcurrentline clause.
    3. If the addressname is 'ShipTo', then you can update the record, and exit loop.
    pseudo code comes below.
    sql = "Select count(*) FROM OCRD WHERE cardcode = 'aaa'"
    ors.doquery sql
    for i=1 to ors.fields.item(0)
    oBusinessPartners.Addresses.setcurrentline(i)
    if obusinessPartners.Addresses.AddressName = "ShipTo" then
    oBusinessPartners.block = "newBlock"
    exit for
    end if
    next i
    Hope this useful for you.
    Regards,
    Hyunil choi.

  • Primary Key in INSERTs

    Hi!! :-)
    Im currently trying to access some Postgres-database from an Enterprise-App running inside Sun App Server 9... Some of th tables have a primary-key-field with type SERIAL, so Postgres creates the value for those fields!!
    Now: How can i achieve, that the app-server does not try to write into those fields??
    Specifying insertable=false is ignored and when i specify insertable=false and updatable=false i get the following error on deployment:
    Deploying application in domain failed; Exception [TOPLINK-0] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.IntegrityException Descriptor Exceptions: --------------------------------------------------------- Exception [TOPLINK-46] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.DescriptorException Exception Description: There should be one non-read-only mapping defined for the primary key field [dsl_payments.id]. Descriptor: RelationalDescriptor(de.meitnerweg.netzag.dsl.persistence.DslPayment --> [DatabaseTable(dsl_payments)]) Runtime Exceptions: --------------------------------------------------------- Exception [TOPLINK-0] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.IntegrityException Descriptor Exceptions: --------------------------------------------------------- Exception [TOPLINK-46] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.DescriptorException Exception Description: There should be one non-read-only mapping defined for the primary key field [dsl_payments.id]. Descriptor: RelationalDescriptor(de.meitnerweg.netzag.dsl.persistence.DslPayment --> [DatabaseTable(dsl_payments)]) Runtime Exceptions: ---------------------------------------------------------
    Anyone ideas??
    :-)

    The blog here describes how to work with this situation.
    http://blogs.sun.com/Glassfish_PostgreSQL/entry/introducing_support_for_postgresql_in
    Look into known Issues / Workaround sections.

  • Autogenerated Primary key

    Hi All,
    I am designing a database.
    But there is no such field so that i can consider it as primary key.
    so is there anything in sap which auto-generates a unique which will act as a primary key for that table?
    As far I know there is a autogenerated field  in MSSQL to solve the above problem, but is there something same  provided  in SAP?
    Please help...............
    Points will be rewarded...........

    Hi guru,
    1. But there is no such field so that i can consider it as primary key
    Then we have to design the table
    in such a manner
    that we can detect a UNIQUE record.
    (If we cannot detect, then how will the system
    detect the unique record which we may require)
    (U may try to put a extra
    field eg. SEQNR (sequence nubmer)
    as a part of the primary key,
    so if some values are going to repeat)
    2. but is there something same provided in SAP?
    No.
    Primary key is compulary.
    We have to do it.
    regards,
    amit m.

  • Missing Primary Keys after migartion of a MSAccess 2003 DB to oracle 9.i

    I migrate a MS Access 2003 DB to Oracle 9.i with the Oracle Migration Workbench 10.1.0.4.0. on a Windows 2k PC. All the Primary Keys of my tables are missed after migration and no Foreign Key is created.
    In the MS Access Source Model Window of OMWB are the Primary Keys detected but in migration script or in oracle db after migration there is no Primary Key applied.
    Dos anyone kows the reason for this behavior.
    Thanks for help in advance.
    Message was edited by:
    user468547
    Message was edited by:
    user468547

    Here the summary of the Model.
    Not mentioned parts are sero in the Oracle Model
    MS Access Source Model
    Table Violation Rules (0)
    Relations ( 48)
    Indexes (96)
    Primary Keys (38)
    Queries (0)
    Tables (38)
    Oracle Model
    Database (1)
    Check Constraints (0)
    Foreign Keys (48)
    Indexes (96)
    Primary Keys /Unique ... (0)
    Tables (38)
    Types (2)
    In the migration scripts the commands for creation of Foreign Keys are avaliable and delievers the error message ORA-02270. e.g.
    REM
    REM Message : Failed to create foreign key: dbwines.TBL_SERVICEPROFILESTBL_UETYPES; ORA-02270: no valid Primr- o. eindeutiger Key for this column
    Here the content of the error.log
    ** Workbench Repository : Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@pcathlon17002:1521:ORCL
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : MSAccess
    oracle.mtg.migration.MigrationSQLException: Failed to get information about Oracle Model Object.
    Erschpfte Ergebnismenge:Failed to get information about Oracle Model Object.
    Erschpfte Ergebnismenge
         at oracle.mtg.oracleModel.server.OracleModelImpl.getObjectInformation(OracleModelImpl.java:476)
         at oracle.mtg.oracleModel.ui.OracleModelTypes.getAllChildren(OracleModelTypes.java:95)
         at oracle.mtg.plugin.ui.WorkbenchAllTreeNode.getChildren(WorkbenchAllTreeNode.java:133)
         at oracle.mtg.migrationUI.TreeDataSource.getItemCount(TreeDataSource.java:128)
         at oracle.ewt.dTree.DTreeDeferredParent.getItemCount(Unknown Source)
         at oracle.ewt.dTree.DTreeBaseItem.isExpandable(Unknown Source)
         at oracle.ewt.dTree.DTreeButtonDecoration.getHasButton(Unknown Source)
         at oracle.ewt.dTree.DTreeButtonDecoration.paintDecoration(Unknown Source)
         at oracle.ewt.dTree.DTreeStackingDecoration.paintDecoration(Unknown Source)
         at oracle.ewt.dTree.DTree.paintCanvasInterior(Unknown Source)
         at oracle.ewt.EwtComponent.paintInterior(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter._paintInterior(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paint(Unknown Source)
         at oracle.ewt.lwAWT.BufferedApplet.paint(Unknown Source)
         at oracle.ewt.lwAWT.BufferedApplet.update(Unknown Source)
         at sun.awt.RepaintArea.paint(Unknown Source)
         at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    ** Shutdown : Mon Apr 10 18:36:10 CEST 2006
    ** Oracle Migration Workbench
    ** Production
    ** ( Build 20050629 )
    ** OMWB_HOME: C:\oracle\ora92\omwb
    ** user language: de
    ** user region: null
    ** user timezone:
    ** file encoding: Cp1252
    ** java version: 1.4.2_04
    ** java vendor: Sun Microsystems Inc.
    ** o.s. arch: x86
    ** o.s. name: Windows 2000
    ** o.s. version: 5.0
    ** Classpath:
    ..\lib\boot.jar
    ** Started : Mon Apr 10 18:36:14 CEST 2006
    ** Workbench Repository : Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@pcathlon17002:1521:ORCL
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : MSAccess
    EXCEPTION : query()java.sql.SQLException: Stream wurde schon geschlossen
    select MESSAGE_TYPE, LOG_ID, TO_CHAR(LOG_DATE, 'dd-MM-yyyy hh24:mi:ss') LOG_DATE, PROJECT_ID, PHASE, SUBPHASE, LOG_MESSAGE, OBJECT_TYPE, OBJECT_ID, CONTEXT_DATA from MTG_LOG_TABLE WHERE PROJECT_ID = 1 and (MESSAGE_TYPE != 9999) ORDER BY LOG_ID ASC
    java.lang.NullPointerException
         at oracle.mtg.migration.LogDisplayUtility.convertToDisplayStrings(LogDisplayUtility.java:185)
         at oracle.mtg.migrationServer.LoggingImpl.getLogs(LoggingImpl.java:482)
         at oracle.mtg.migrationUI.LoggingPane.setupLogTable(LoggingPane.java:291)
         at oracle.mtg.migrationUI.LoggingPane.setupLogTable(LoggingPane.java:280)
         at oracle.mtg.migrationUI.ProgressDialog.commandStarting(ProgressDialog.java:117)
         at oracle.mtg.migrationUI.MigrationUI.commandStarting(MigrationUI.java:2427)
         at oracle.mtg.migrationUI.MigrationWizard.doMigrate(MigrationWizard.java:401)
         at oracle.mtg.migrationUI.MigrationWizard.runDialog(MigrationWizard.java:293)
         at oracle.mtg.migrationUI.ActionMenuHandler._migrate(ActionMenuHandler.java:340)
         at oracle.mtg.migrationUI.ActionMenuHandler._capture(ActionMenuHandler.java:291)
         at oracle.mtg.migrationUI.ActionMenuHandler.run(ActionMenuHandler.java:85)
         at oracle.mtg.migration.WorkerThread.run(Worker.java:268)
    ** Workbench Repository : Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@pcathlon17002:1521:ORCL
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : MSAccess
    Thaks for help in advance
    Regards Steffen

  • How to get the new Primary Key after the Automatic Row Processing (DML)

    Hi,
    I have a nice master detail form.
    I want, immediately after submitting the page when creating a new record in the master table, that the user may input the associated table (the detail table). For that I have created a branch that goes back to the very same page after creating the record (ie submitting the page with the button Create). In the Action of the branch, i have put P30_FICHE_ID (the item containing the primary key of the master table) with its value : &P30_FICHE_ID.
    Unfortunately I see that the item is not populated with the very new primary key. it seems normal becaus after submitting the page the tiem is not populated. This is my question : how to retrieve the newly created primary into the item P30_FICHE_ID in order to begin immediately to add rows to the detail table ?
    Hope I'm clear. My english not perfect.
    Thank you for your kind help !
    Christian
    Edited by: Christian from France on Oct 16, 2009 6:36 AM

    Christian,
    After creating Master-detail form, goto your Detail page. In this page you can see one conditonal brach which will point to 'Master' page.
    Edit this branch and here you can see this branch fires when request is in 'SAVE,DELETE,CREATE' (in Expression1). Now change the value in Expression1 to 'SAVE,DELETE'. This will do the needful :-)
    Cheers
    Hari
    Edited by: Hari_639 on Oct 16, 2009 8:02 PM

  • How can i set primary key after creating a table ?

    hi friends
    thank you for all the support you have given me . i have doubt ,can we set primary key for a column after creating the table
    I have added a column named idno after creating the table . i want to set that column as primary key . i tried this
    table name = address
    column name = idno
    ALTER TABLE ADDRESS MODIFY (idno PRIMARY KEY(idno))
    ,but not working
    if anbody knows the solution pls reply
    thanks and regards
    nev

    how does the other users know which is the primary key for this table?....the other user needs to execute this query...and modify the query accordingly
    select aa.table_name,aa.column_name,aa.constraint_name,bb.constraint_type
    from user_cons_columns aa,user_constraints bb
    where aa.constraint_name = bb.constraint_name
    and aa.table_name = 'TEST_EMP' and bb.constraint_type = 'P';

  • Missing primary keys after import

    Hi,
    We receive a .dmp file from another company each night. The process changed when they started to obfuscate some sensitive data. But since then we are finding all the tables are missing their primary keys.
    I really would like to eliminate our import process as the cause.
    Has anyone ever heard of this kind of problem before? What was the cause/scenario.
    Your help is greatly appreciated.
    Brian

    If you are not getting any errors during the import process, it is pretty unlikely that the import process is at fault assuming that hasn't changed. Make sure that INDEXES=Y and CONSTRAINTS=Y are specified (which is the default).
    You can use the SHOW=Y parameter to have the import utility write the DDL contained in the dump file to a text file where you can manually verify that the primary key constraints you were expecting are indeed missing.
    Justin
    Edited by: Justin Cave on Nov 10, 2008 3:44 PM
    typo

  • How to get the inserted row primary key with out  using select statement

    how to return the primary key of inserted row ,with out using select statement
    Edited by: 849614 on Apr 4, 2011 6:13 AM

    yes thanks to all ,who helped me .its working fine
    getGeneratedKeys
    String hh = "INSERT INTO DIPOFFERTE (DIPOFFERTEID,AUDITUSERIDMODIFIED)VALUES(DIPOFFERTE_SEQ.nextval,?)";
              String generatedColumns[] = {"DIPOFFERTEID"};
              PreparedStatement preparedStatement = null;
              try {
                   //String gen[] = {"DIPOFFERTEID"};
                   PreparedStatement pstmt = conn.prepareStatement(hh, generatedColumns);
                   pstmt.setLong(1, 1);
                   pstmt.executeUpdate();
                   ResultSet rs = pstmt.getGeneratedKeys();
                   rs.next();
    //               The generated order id
                   long orderId = rs.getLong(1);

  • ?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...

  • Very Common Scenario - Insert new Rows whose primary Key is not in View Obj

    Question : How can you add new records when the primary key of the records are not present in view ? I am facing infinite loop for the below logic .
    The View Object is derived from 2 entity object (tableA,tableB) . The view has created in such a way that tableA data is updatable and tableB is read only. The view contains all the unique records of tableA and tableB . i,e the SQL query returns all the existing records from tableA , and those are not in tableA picks from tableB . Therefore , the Sql Query returns the primary key of tableA as 0 for the records which are not present in tableA but exist in tableB .
    there fore My sql qery like below
    select A.P_ID, A.mapping_id, A.dataValue FROM tableA A
    UNION select  0 P_ID ,  B.mapping_id , 0 dataValue From tableB  B ;
    Now my challenge is how can to add those new records that taken from table B and insert to TableA ? I am getting an infinite loop for the below logic -
    Below code has been written in my Managed bean -
    public void addNewSelectedMappings(){
    DCBindingContainer dcb = (DCBindingContainer)evaluateEL("#{bindings}");
    DCIteratorBinding dciter =
    dcb.findIteratorBinding("CustomView1Iterator");
    ViewObject vo = dciter.getViewObject();
    Row row = null;
    while ((row = vo.getCurrentRow()) != null)
    Number mappingId =
    (oracle.jbo.domain.Number)row.getAttribute("mappingId");
    java.lang.Number dataValue = ( java.lang.Number)row.getAttribute("dataValue ");
    if(mappingId .equals(0)){
    BindingContext bindingContext = BindingContext.getCurrent();
    BindingContainer bindings = bindingContext.getCurrentBindingsEntry();
    // call the client interface defined in the AM
    OperationBinding methodWithArgs = (OperationBinding) bindings.get("insertNewRow");
    //add argument
    methodWithArgs.getParamsMap().put("mappingId",mappingId);
    methodWithArgs.getParamsMap().put("dataValue ",dataValue);
    methodWithArgs.execute();
    vo.next();
    Below code in my application module to execute -
    +public String insertNewRow(oracle.jbo.domain.Number mappingId , java.lang.Number  dataValue){+
    +try{+
    SequenceImpl seq = new SequenceImpl("TableA_ID_SEQ", getDBTransaction());
    oracle.jbo.domain.Number  seqNextval = seq.getSequenceNumber();
    System.out.println(" seqNextval " seqNextval);+
    ViewObject vo = this.getCustomView1();
    Row r = vo.createRow();
    r.setAttribute("P_Id", seqNextval);*
    r.setAttribute("mappingId ", mappingId );
    r.setAttribute("dataValue", dataValue);
    vo.insertRow(r);
    this.getDBTransaction().commit();
    +} catch (oracle.jbo.TooManyObjectsException tmoe) {+
    System.out.println(" eorrr......"tmoe);+
    return "error";
    +} catch ( RowAlreadyDeletedException rd) {+
    System.out.println(" Inside RowAlreadyDeletedException ");
    return "RowAlreadyDeletedException";
    +}+
    return "success";
    +}+

    Hi ,
    Can some one please help me out . Just to simplify the question , I have a mappings table and a Master table .
    All the user selected items should save in the Mapping table . let say , there is a table name Products . User selects the products and that should save in the User product mapping table .
    I want to show the user selected products and available products in a single view . also , want to update the mappings table based on user selection .
    i m using jdev 11.1.1.5 .

Maybe you are looking for

  • Desktop Manager 6.0 stopped working

    For no apparent reason my DM version 6 stopped working yesterday.  I have de- and re-installed it and rebooted with no improvement.  When the application opens I see a partially loaded screen.  Very limited text and drop down arrows that do nothing,

  • Sales order create with reference to contract order

    Hi,         I am trying to create a sales order with reference to an existing contract order. I have given the contract order and clicked on the selection-list button to select the items I want to copy. It listed the items, but I am not getting all t

  • In iPhoto why does a slide show  from an album run in reverse?

    Under OSX 10.9 in iPhoto why does a slideshow from an album run in reverse?

  • Attaching objects

    Dear Experts, In order to attach a BO to my workitem I am using, put a binding in the task with the wf container for the object to adhoc_objects, i.e. &INCOMINGINVOICE&     to &_ADHOC_OBJECTS&. where incominginvoice is the wf container for the object

  • Cronjob to run in every 40 days

    HI, I want to schedule one cronjob to run once in every 40 days. Please suggest what would be exact cronscript for this. Thanks, Saurabh