Autofill primary key with another field

I have 2 fields:
DISTRIB_CODE ex. ABC
DISTRIBUTOR ex. ABC COMPANY
I want the DISTRIB_CODE to be the primary key, but I cannot do that because DISTRIB_CODE occasionally changes. So, I think I thought of a way to work around it:
DISTRIB_ID (PK constraint)
DISTRIB_CODE (Unique Key constraint) ex. ABC
DISTRIBUTOR ex. ABC COMPANY
I want DISTRIB_ID to auto-fill when I enter a code into DISTRIB_CODE.
Example: When I enter "ABC" into DISTRIB_CODE I want DISTRIB_ID to auto-fill with "abc".
Can this be done? Are there any negatives of doing this? I am a BEGINNER, so please be detailed.
Thank you.

Hi James,
I appreciate that using a sequence based primary key is not the same as an updatable one. However, if the PK is updatable and is intended for use elsewhere within the database as a foreign key, you would also need to have cascade-update switched on to ensure that all child tables are updated with any new value. The only thing that you would need when using a sequential PK is a unique constraint on the distrib_code field to ensure that duplicates are not possible.
Additionally, if the PK remains updatable, using javascript to populate it based on the second field would only be part of the process as you would still need item or page validation to ensure that it is unique before attempting to write the data into the table.
So, I think it would be easier all round if the PK was numeric and sequential, the distrib_code column had a unique constraint defined on the table and that there is item or page validation that checks for duplicates and returns user-friendly messages to the user.
Regards
Andy

Similar Messages

  • Updating primary key with jdbc

    Trying to update a primary key with:
    public static void updateTAXID(String coid,String accountnumber,String oldTAXID,String fundname,String newTAXID){ Properties props = TradeHelper.loadProperties(); Connection conn = null; PreparedStatement st = null; String sql ="update FinancialAccount set taxid=? " + "where dealernumber=? and " + "taxid=? and " + "fundname=? and " + "accountnumber=?"; try{ Class.forName(props.getProperty("driver")); conn = DriverManager.getConnection(props.getProperty("brokerageurl"), props.getProperty("user"),props.getProperty("password")); st = conn.prepareStatement(sql); st.setString(1, newTAXID); st.setString(2, coid); st.setString(3, oldTAXID); st.setString(4, fundname); st.setString(5, accountnumber); st.executeUpdate(); System.out.println("Update: new tx:"+newTAXID+":"+"Ol tx: "+oldTAXID+" act:"+accountnumber); conn.close(); st.close(); }catch(Exception e){ e.printStackTrace(); } }
    I keep getting this error:
    com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '02673025561-QA-SLFCA-' for key 'PRIMARY'         at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1011)         at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)         at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)         at com.mysql.jdbc.PreparedStatement.exe
    Am I not able to update a single field of a composit key with jdbc? Whay is my update failing telling that there is a duplicate when I am trying to update?

    iketurner wrote:
    I keep getting this error:
    com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '02673025561-QA-SLFCA-' for key 'PRIMARY'
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1011)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
    at com.mysql.jdbc.PreparedStatement.exeAm I not able to update a single field of a composit key with jdbc? Whay is my update failing telling that there is a duplicate when I am trying to update?If you take the error message at its word then the problem is not that you are not permitted to update a primary key but that the values you are trying to use is already in use.
    I'll leave it you DBA and/or Data Modeler/Architech to decide if it is a good idea to update the value or not.

  • Creating a primary key with the parallel option and the tablespace option

    I know I can create a unique index with these options and then make the primary key with the "using index" clause. anyway to do this and skip the create unique index and just create the primary key ?

    SQL> ALTER TABLE t
      2  ADD CONSTRAINT pk_t
      3  PRIMARY KEY (testcol)
      4  USING INDEX
      5  TABLESPACE example
      6  PARALLEL (DEGREE 2);
    PARALLEL (DEGREE 2)
    ERROR at line 6:
    ORA-03001: unimplemented featureYou can name the tablespace but you must do an alter index thereafter.

  • Primary Key With Four Column ,How to use that Column As Primary Key In Form

    Dear All,
    i have create composite Key as primary Key With Four Column .
    How can i use these column in Form With Report Page.
    How can i use these four Column as primary Key to Edit Record .
    How can i do this.
    Thanks
    Vedant

    wrap a view around your table with this bogus primary key. Use an instead of trigger to handle the inserts and updates. And then look at using surrogate keys to resolve these bad design issues...
    5 out of 4 people don't understand fractions.
    Thank you,
    Tony Miller
    Webster, TX

  • Utilizing auto-increment/identity fields for primary key with "application" identity

    Is it possible to utilise an auto-increment (identity in MS SQL Server)
    field for the primary key field when using "application" identity?

    To the best of my knowledge, you cannot use auto-increment. Due to the
    differences in the way that identities are generated at the datastore
    (upon insert) vs. JDO (upon makePersistent), this feature of SQLServer is
    not supported yet.
    However, we do provide a variety of other ways of generating identity
    which may provide a closer fit to what you want, and
    our users may have some experience in solving your problem.
    On Tue, 28 Jan 2003 09:56:08 +0000, Sean Ryan wrote:
    Is it possible to utilise an auto-increment (identity in MS SQL Server)
    field for the primary key field when using "application" identity?--
    Stephen Kim
    [email protected]
    SolarMetric, Inc.
    http://www.solarmetric.com

  • Populate Primary Key with DBSequence in ADF UIX page

    I have a table with a trigger, so that the primary key is populated by DBSequence. My problem is, I open a ADF UIX Input Page to create a row for my table. The field of the primary key is populated by any number but not with the logical sequence number. This number appears later, when I look at a row list. So the correct number is in the database but how can this already appear on my input page???

    You have to drop the trigger.
    Then make sure you have the Id field of your entity of type Sequence.
    Then go to your entity class and override the Create method.
      protected void create(AttributeList attributeList)
        super.create(attributeList);
        SequenceImpl s = new SequenceImpl("YOUR_DB_SEQUENCE_NAME", getDBTransaction());
        Number sVal = s.getSequenceNumber(); 
        setId(new DBSequence(sVal));

  • Out of Order Primary Keys and Blob fields

    Hi,
    I am using Oracle Migration Workbench to transfer the data from SQLServer 2000 to ORacle 9i. I am running into the following issues and was wondering if you had any ideas what may be going on:
    1.) Primary keys are out of order
    2.) Blob fields are inserted into the incorrect row
    Ex. BLOB field stating 'Application active' should be associated with Act_key (primary key) = 5 and it ends up transfering over with act_key 28.
    Thank you for any information you may have on this.
    AK

    I am very interested in this thread because I have encountered a similar problem with BLOB columns, except that I am also seeing this with CLOB's.
    Essentially the all the data gets 'migrated', but the CLOB and BLOB columns are all mixed up!
    Any solutions?

  • Error when i set primary key to a field in table

    I created a table. with one primary key field
    on saving it following error happened 
    at Microsoft.SqlServer.Management.DataTools.Interop.IDTDocTool.Save(Object dsRef, String path, Boolean okToOverwrite)
    at Microsoft.SqlServer.Management.UI.VSIntegration.Editors.VsDataDesignerNode.Save(VSSAVEFLAGS dwSave, String strSilentSaveAsName, IVsUIShell pIVsUIShell, IntPtr punkDocDataIntPtr, String& strMkDocumentNew, Int32& pfCanceled)
    then i removed primary key. Table was saved successfully.
    I need to make primary key field.. how can i solve it?

    CREATE TABLE tblname (c INT NOT NULL PRIMARY KEY) 
    Have you ran the above statement successfully?  Do you create a table in VS?  
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • ON UPDATE CASCADE and Autoincrement primary key with Oracle SQL Developer

    hello everybody,
    I want to know if Oracle SQL Developer manage autoincrement on primary key and "ON UPDATE CASCADE" when i migrate (with data) SQL Server database in Oracle database.
    Can you help me ?
    Thanks for your suggestions.

    Obtain the value of the auto increment key with the getGeneratedKeys() method.
    Statement stmt = null;
    ResultSet rs = null;
    stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                                    java.sql.ResultSet.CONCUR_UPDATABLE);
    stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTable");
        stmt.executeUpdate(
                "CREATE TABLE autoIncTable ("
                + "priKey INT NOT NULL AUTO_INCREMENT, "
                + "dataField VARCHAR(64), PRIMARY KEY (priKey))");
    stmt.executeUpdate(
                "INSERT INTO autoIncTable  (dataField) "
                + "values ('data field value')",
                Statement.RETURN_GENERATED_KEYS);
    int autoIncKeyFromApi = -1;
        rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            autoIncKeyFromApi = rs.getInt(1);
        } else {
        rs.close();

  • Problems Engineering Surrogate Primary Key with Unique Key

    SDDM 3.3.0.747 with 2 problems (at least so far).  I am hoping that the problem is with this SDDM rookie and I have overlooked some setting. PROBLEM 1 I don’t want to start a religious debate about surrogate vs. natural keys but I am having a problem engineering both correctly from the logical model.  I am a rookie when it comes to SDDM but have many years of experience with Designer. By default I like to have both a natural UID  (UK) and a surrogate key based primary UID (PK) which is used for foreign keys.  The problem I am having with engineering is I can successfully engineer the surrogate PK’s, engineer the FK’s using the PK’s but cannot get the unique key to contain the surrogate keys in the child table.  If I check the identifying property in the relations, the PK columns and the UK columns are included in the child PK and the UK contains no columns. The Setup I have defined two reference entities, PROBABILITY and SEVERITY with natural unique keys defined.  I also have a child entity RISK_ASSESMENT with relationships back to the PROBABILITY and SEVERITY entities and both have the “Use surrogate keys:”: check box checked.  The unique key for the RISK_ASSESMENT entity includes the relationships back to PROBILITY and SEVERITY.  None of the entities have a PK or surrogate key defined and they all have the “Create Surrogate Key” check box checked.  In addition the following preferences are set: Data Modeler/Model/Logical   NOT Checked - Use And Set First Unique Key As Primary Key   NOT Checked – Name – Keep as the name of the Originating attribute   Checked – Entity Create Surrogate Key   Checked – Relationship Use Surrogate Key PROBLEM 2 When the foreign key columns are engineered I want the names to have a prefix “FK_” but they don’t.  Templates are set as follows: Data Modeler/Naming Standard/Templates   Foreign Key:  FK_{child}{parent}   Column Foreign Key:  FK_{ref column} Engineer to Relational Model/General Options   Checked - Apply name translation Marcus Bacon

    I have been switching between SD 4 EA1 and SDDM 3.3 trying to get things to work and trying out the template table for adding audit columns (really nice!).
    Concerning Problem1.  No matter what settings I use and whether I use SDDM 3.3 or SDI cannot get the FK columns to be included in the UK even though the relations are included in the UID in the entitty.  When I open the properties of the child table and click on the naming standards button and click ok it complains that the UK is not complete.  I add the FK columns to the UK and all is well including the naming standards.
    Concerning Problem 2.  Sometimes it engineers the names for FK's from the template and sometimes it doesn't.  Didn't see a pattern.  Gave up trying and used Naming Standards button.  I still had to change a few.
    The good new is, that after make changes needed in UK's and Column names of 18 tables, I know have everything deployed to Test except FK Indexes.  I think I have to do those by hand.
    Marcus Bacon

  • Can the Primary Key also be Primary key in another table

    Hi all,
    I am working on a project. The project specification says:
    Project table contains details of projects and the project number *(proj_no)* is the key.
    project ( proj_no , proj_date, proj_desc, proj_type, proj_status, s_no, cust_no)
    purchase_order table contains details of the purchase orders for each project and the combination of project
    number and a purchase order number *(proj_no, po_no) form the key.*
    purchase_order ( proj_no , po_no, po_date)
    How can I have proj_no in the project table and in the purchase_order as primary keys?
    If I create a composite key in the purchase_order table making the ( proj_no, po_no) as primary key. How can I make the project_no in the project table a primary key too?
    Is there a solution for it?
    CREATE TABLE purchase_order(
    po_no NUMBER(5) NOT NULL,
    proj_no NUMBER(5) NOT NULL,
    po_date date,
    CONSTRAINT p_o_po_no_proj_no_pk PRIMARY KEY (po_no,proj_no));
    Thanks!!!

    Hi,
    I think I'd set the project no in the projects table a primary key, and project no in the purchase orders table a foreign key constraint to the projects table, combined with a unique, not null constraint in the table.
    That, in addition to a unique, not null constraint on the purchase orders column, and a composite primary key should fulfill the requirements.
    Best of luck!
    Johan

  • How to map a table with out a primary key with a pojo?

    hello
    Is it possible to map a pojo with a table, table don't have primary key. I m using hibernate,How to do that in hibernate.
    Thanks &Regards
    snimi

    Hello,
    EclipseLink has support for database object-relational datatypes, but they are not supported or exposed through JPA. Instead, you will need to leave it unmapped and then change the mapping, using a customizer to create the mapping described:
    http://wiki.eclipse.org/Introduction_to_Object-Relational_Data_Type_Mappings_(ELUG)#Object-Relational_Data_Type_Array_Mapping
    Best Regards,
    Chris

  • Update primary key with a tabular form based on a select list for each row

    Hello!
    I've two tables: Table1 with only one column (primary key) is a foreign key for table2.column1 (primary key). There is also a second primary key column in table2.
    Now I want to change the primary key values in table2.column1 with a tabular form (MRU) based on a select list (LOV based on table1.column1) for each row.
    The user should be able to choose for every row a new value from the select list to change the old primary key value at this position.
    How can I do this with ApEx?
    I've the tabular form and so on, but at the moment I get the following error:
    "Error in mru internal routine: ORA-20001: Fehler in MRU: row= 1, ORA-20001: ORA-20001: Die aktuelle Version der Daten in der Datenbank wurde geändert, seit der Benutzer einen Update-Prozess eingeleitet hat. ..."
    Thank you for your support!
    Kay

    Hello!
    I've two tables: Table1 with only one column (primary key) is a foreign key for table2.column1 (primary key). There is also a second primary key column in table2.
    Now I want to change the primary key values in table2.column1 with a tabular form (MRU) based on a select list (LOV based on table1.column1) for each row.
    The user should be able to choose for every row a new value from the select list to change the old primary key value at this position.
    How can I do this with ApEx?
    I've the tabular form and so on, but at the moment I get the following error:
    "Error in mru internal routine: ORA-20001: Fehler in MRU: row= 1, ORA-20001: ORA-20001: Die aktuelle Version der Daten in der Datenbank wurde geändert, seit der Benutzer einen Update-Prozess eingeleitet hat. ..."
    Thank you for your support!
    Kay

  • 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);

  • Table creation from type - Primary key with 2 columns

    Hello,
    I have to create a table from a type that I created.
    The thing is that I want to create a primary key using two column.
    Because this table is junction table.
    How can I do this ?
    CREATE TABLE CONTENT OF CONTENT_T (ID_COMP primary key, ID_CHAR_J NOT NULL PRIMAR
    Y KEY);
    Oracle return:
    CREATE TABLE CONTENT OF CONTENT_T (ID_COMP primary key,ID_CHAR_J NOT NULL PRIMARY KEY)
    ERROR at line 1:
    ORA-02260: table can have only one primary key
    So I tried:
    CREATE TABLE CONTENT OF CONTENT_T (ID_COMP,ID_CHAR_J NOT NULL PRIMARY KEY)
    ERROR at line 1:
    ORA-02338: missing or invalid column constraint specification
    Tahnk's in advance.
    Edited by: user8266437 on 29 avr. 2009 13:56
    Edited by: user8266437 on 29 avr. 2009 13:56

    SCOTT@orcl_11g> CREATE OR REPLACE TYPE content_t AS OBJECT
      2    (id_comp    NUMBER,
      3       id_char_j  VARCHAR2 (10),
      4       other_cols VARCHAR2 (10));
      5  /
    Type created.
    SCOTT@orcl_11g> CREATE TABLE CONTENT OF CONTENT_T (PRIMARY KEY (ID_COMP, ID_CHAR_J))
      2  /
    Table created.
    SCOTT@orcl_11g> INSERT INTO content VALUES (content_t (1, 'A', 'WHATEVER'))
      2  /
    1 row created.
    SCOTT@orcl_11g> COMMIT
      2  /
    Commit complete.
    SCOTT@orcl_11g> INSERT INTO content VALUES (content_t (1, 'A', 'DUPLICATE'))
      2  /
    INSERT INTO content VALUES (content_t (1, 'A', 'DUPLICATE'))
    ERROR at line 1:
    ORA-00001: unique constraint (SCOTT.SYS_C0062057) violated
    SCOTT@orcl_11g> COMMIT
      2  /
    Commit complete.
    SCOTT@orcl_11g> SELECT * FROM content
      2  /
       ID_COMP ID_CHAR_J  OTHER_COLS
             1 A          WHATEVER
    SCOTT@orcl_11g>

Maybe you are looking for