How to create Primary key

I want to insert HOSTID that has unique values in a new application in a primary key column in database.
I am starting with h000000001
and I want to go from that to h000000002
and .... h0000000010 , 11, 12 etc etc.
How do I do this?
I did this:
rs = stmt.executeQuery("select wlbmach_host_id from wlbmach order by wlbmach_host_id desc");
// I am getting the greatest value eg: h000999999
if (rs.next())
getHostID = (String)rs.getString("wlbmach_host_id");
//Get the h0009999999
getStringNumber = getHostID.substring(1,10);
//This gives me 9999999
try
{getNum = Integer.parseInt(getStringNumber);
//change number to integer so I can add 1 to it
getNum=getNum+1;
getStringNumber=Integer.toString(getNum);//make that a string
getHostID="h"+getNum;//add h to it
}//try
catch(Exception e)
{System.out.println("NumberFormatException might have occured");%>
else
     System.out.println("Assigning first HostID");
     getHostID = "h00000001";
System.out.println("HostID is "+getHostID);
But gives Exception:String index out of range: 10.. My column can take 10 varchar ??
Can someone help .. Is this the right way to do it ?
Is there a better way to generate primay keys?

Why are you making life difficult??? Why not use the SEQUENCE object (if you are using Oracle)? You can retrieve next value by "Select sequencename.nextval from dual" as the query...you will get your number. Also, when two requests are made at the same time, Oracle takes care of this problem for you...you do not need to synchronize the method in JAVA. Do some research in this...I think you will like it.

Similar Messages

  • How to Create primary key index with duplicate rows.

    Hi All,
    While rebuilding an index on a table , I am getting error that there are duplicate rows in a table.
    Searching out the reason led me to an interesting observation.
    Please follow.
    SELECT * FROM user_ind_columns WHERE table_name='SERVICE_STATUS';
    INDEX_NAME     TABLE_NAME     COLUMN_NAME     COLUMN_POSITION     COLUMN_LENGTH     CHAR_LENGTH     DESCEND
    SERVICE_STATUS_PK     SERVICE_STATUS     SUBSCR_NO_RESETS     2     22     0      ASC
    SERVICE_STATUS_PK     SERVICE_STATUS     STATUS_TYPE_ID     3     22     0     ASC
    SERVICE_STATUS_PK     SERVICE_STATUS     ACTIVE_DT     4     7     0     ASC
    SERVICE_STATUS_PK     SERVICE_STATUS     SUBSCR_NO     1     22     0     ASC
    SELECT index_name,index_type,table_name,table_type,uniqueness, status,partitioned FROM user_indexes WHERE index_name='SERVICE_STATUS_PK';
    INDEX_NAME     INDEX_TYPE      TABLE_NAME     TABLE_TYPE     UNIQUENESS     STATUS     PARTITIONED
    SERVICE_STATUS_PK     NORMAL     SERVICE_STATUS     TABLE     UNIQUE     VALID     NO
    SELECT constraint_name ,constraint_type,table_name,status,DEFERRABLE,DEFERRED,validated,index_name
    FROM user_constraints WHERE constraint_name='SERVICE_STATUS_PK';
    CONSTRAINT_NAME     CONSTRAINT_TYPE     TABLE_NAME      STATUS     DEFERRABLE     DEFERRED     VALIDATED     INDEX_NAME
    SERVICE_STATUS_PK     P     SERVICE_STATUS     ENABLED     NOT DEFERRABLE     IMMEDIATE VALIDATED     SERVICE_STATUS_PK
    1. Using index scan:
    SELECT COUNT (*)
    FROM (SELECT subscr_no, active_dt, status_type_id, subscr_no_resets
    FROM service_status
    GROUP BY subscr_no, active_dt, status_type_id, subscr_no_resets
    HAVING COUNT (*) > 1) ;
    no rows returned
    Explain plan:
    Operation     OBJECT Name     ROWS     Bytes     Cost     OBJECT Node     IN/OUT     PStart     PStop
    SELECT STATEMENT Optimizer MODE=CHOOSE          519 K          14756                     
    FILTER                                        
    SORT GROUP BY NOSORT          519 K     7 M     14756                     
    INDEX FULL SCAN     ARBOR.SERVICE_STATUS_PK     10 M     158 M     49184                     
    2. Using Full scan:
    SELECT COUNT (*)
    FROM (SELECT /*+ full(s) */ subscr_no, active_dt, status_type_id, subscr_no_resets
    FROM service_status s
    GROUP BY subscr_no, active_dt, status_type_id, subscr_no_resets
    HAVING COUNT (*) > 1) ;
    71054 rows returned.
    Explain Plan:
    Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
    SELECT STATEMENT Optimizer Mode=CHOOSE          1           24123                     
    SORT AGGREGATE          1                               
    VIEW          519 K          24123                     
    FILTER                                        
    SORT GROUP BY          519 K     7 M     24123                     
    TABLE ACCESS FULL     ARBOR.SERVICE_STATUS     10 M     158 M     4234                     
    Index SERVICE_STATUS_PK is a unique and composite primary key VALID index. And the constraint is ENABLED and VALIDATED still having duplicate rows in table.
    How it is possible?
    Is it an Oracle soft Bug??
    Regards,
    Saket Bansal

    saket bansal wrote:
    Values are inserted as single rows inserts through an GUI interface.And you still claim to have over 71K duplicate records, without the GUI getting any kind of errors?
    That does not add up and can only be explained by a "bug".
    I tried inserting a duplicate record but failed.
    SQL> insert into service_status (select * from service_status where rownum <2);
    insert into service_status (select * from service_status where rownum <2)
    ERROR at line 1:
    ORA-00001: unique constraint (ARBOR.SERVICE_STATUS_PK) violatedAre you really sure there is no other way data in this table is populated/manipulated in bulk?

  • What is the best practice for creating primary key on fact table?

    what is the best practice for primary key on fact table?
    1. Using composite key
    2. Create a surrogate key
    3. No primary key
    In document, i can only find "From a modeling standpoint, the primary key of the fact table is usually a composite key that is made up of all of its foreign keys."
    http://download.oracle.com/docs/cd/E11882_01/server.112/e16579/logical.htm#i1006423
    I also found a relevant thread states that primary key on fact table is necessary.
    Primary Key on Fact Table.
    But, if no business requires the uniqueness of the records and there is no materilized view, do we still need primary key? is there any other bad affect if there is no primary key on fact table? and any benifits from not creating primary key?

    Well, natural combination of dimensions connected to the fact would be a natural primary key and it would be composite.
    Having an artificial PK might simplify things a bit.
    Having no PK leads to a major mess. Fact should represent a business transaction, or some general event. If you're loading data you want to be able to identify the records that are processed. Also without PK if you forget to make an unique key the access to this fact table will be slow. Plus, having no PK will mean that if you want to used different tools, like Data Modeller in Jbuilder or OWB insert / update functionality it won't function, since there's no PK. Defining a PK for every table is a good practice. Not defining PK is asking for a load of problems, from performance to functionality and data quality.
    Edited by: Cortanamo on 16.12.2010 07:12

  • How to created Costing Key

    Hi,
    How to create costing key and wwhere to assign for value fields.Kindly provide me the Tcodes for the same.
    I will assgin poiints
    Thanks
    Sunitha

    Hi,
    The tcode to create costing key: KE40
    The tcode to assign value fields: KE4R

  • How to set primary key of the VO.

    I have a problem with the master detail search. The search works fine on the first search, all details can be seen fine, but in the second search I get this error.
    The number of displayed records, 1, exceeds the actual number of records, 0, in view object EgoItemAdvancedSearchAM.MYACCESSOR001_MYLINK001_DetailsOrderLinesVO. Some of the displayed records may have been deleted.
    Somwhere in another thread, someone had the same problem and the soultion was to set primary key of the master VO. I am not sure how to set primary key of a VO. In my case the master VO is dynamic. Is there a way I can set PK of a dynamic VO.
    Any help greatly appreciated.

    Hi
    Thanks for your reply...
    am seting the primary key to VO attribute in my controller(PR)...but its not mapping to the VO attribute..
    OAAttachmentImageBean Ibean = (OAAttachmentImageBean)webBean.findChildRecursive("OpAttachments");
    String[] pkvaule = {"ResAttribute15"};
    Ibean.setPkColumns(pkvaule);
    Regards
    Harrrry

  • How to find Primary Key for a particular SAP Databse Table?

    Hi Guys,
                  How to find Primary Key and foreign key  for Particular SAP Databse table ?for Ex : EKKO , EKPO , EKKN , EKBE , EKBEH  , EKET and EKETH.
    Thanks,
    Srinivas.

    Use transaction SE11 to display the table. Put the cursor on the field you want to display the check table and click 'Foreign key' push button (a key with an bottom point arrow), then it will show the check table of the foreign of a field.
    Or by just simple double click on the field, a pop-up window of all the attribute (including the foreign key and the check table if exists) will show too.
    <i><b>Please reward point for helpful answer.</b></i>
    Minami

  • How to create AES keys?

    How to create AES keys in Java Card SDK 2.2.1?
    The manual is confusing.

    The oncard building of an AES key is somehow similar to an DES key.
    On applet installation build an AES key by:
    AESKey key = (AESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_AES,KeyBuilder.LENGTH_AES_128,false);
    //Now you can fill the key with random data.
    key.setKey(randomDataof128bitLength,(short)0);For generationg random data see RandomData.
    But you should keep in mind that most JavaCards only support DES /3DES as symmetric cipher. I only know two card that support AES (g&d SmartCafe Expert 64 and Axalto Cyberflex Access 64 K).
    Jan

  • Do I need to Create Primary Key Class for Entity beans with Local interface

    Do I need to Create Primary Key Class for Entity beans with Local interface?
    I have created my entity bean with the wizard in Sun One Studio and it does not create a primary key class for you.
    I thought that the primary key class was required. My key is made up of only one field.
    Anyone know the answer.
    Jim

    u dont need to create a primary key class for a entity bean.if ur table's primary key feild(int ,float) is a built in or primitive data type,then u dont need one.But if ur table has a primary key field which is non primitive (for example StudentID,ItemID etc)then u have to create a primary key class.
    hope this helps :-)

  • How to get primary keys in some order with joins?

    Hi, I build BBS using BDB as backend database, forum database, topic database and post database share one environment. This BBS web application is multi-thread program. If user selects one forum, its topics will be listed in order of last reply time;selecting one topic, posts are listed in order of reply time as well.
    struct forum {
    UInt16 forumID;
    string forumName;
    string _lastPoster;      // who is the last one replied in this forum
    struct topic {
    UInt32 topicID;
    UInt16 forumID; // topic comes from this forum
    string title; // topic title
    UInt64 dateOfLastReply; // when last reply to this topic happen
    struct post {
    UInt64 postID;
    UInt32 topicID; // post comes from this topic
    string title; // post title as of topic
    UInt64 dateOfPost; // when this post is created
    I create one primary database and two secondary databases for topic, primary key is topicID, secondary key are forumID and dateOfLastReply respectively, and I want to show 1st 25 topics in latest reply time order on the 1st browser page, 2nd 25 topics on the 2nd browser page, and etc.
    if using SQL, it will be: SELECT topicID FROM topic WHERE forumID=xx ORDER BY dateOfLastReply DESC
    From performance perspective, I want get all topics id of one same forum, and need them come in reply time order, then retrieve topic one by one based on returned topicID, how can I do this? guess I have to use joins.
    Plus, do you have any suggestion about retrieval performance given the fact that topics retrieval will happen each time browser want to request the next page, that is, 2nd 25 topics of this forum?
    Is DB_DBT_MULTIPLE helpful to me?
    thanks.
    Edited by: tiplip on 2011-1-22 上午5:43
    Edited by: tiplip on 2011-1-22 下午5:52
    Edited by: tiplip on 2011-1-23 下午7:42

    Hi tiplip,
    Bellow I will describe how you can support "SELECT * FROM table WHERE X = key ORDER BY Y" queries using Berkeley DB, which, as you suspected, should be done by using a composite index.
    First of all, think of Berkeley DB as the storage engine underneath an RDBMS. In fact, Berkeley DB was the first "generic data storage library" implemented underneath MySQL. As such, Berkeley DB has API calls and access methods that can support any RDBMS query. However, since BDB is just a storage engine, your application has to provide the code that accesses the data store with an appropriate sequence of steps that will implement the behavior that you want.
    If you have two indices in SQL, each on a single column (call them X and Y), and you do:
    SELECT * FROM table WHERE X = key ORDER BY Y;then there are three plausible query plans:
    (1) scan the whole table, ignore both indices, filter by X = key then sort by Y;
    (2) use the index on Y to scan all rows in the required order, filter by X = key;
    (3) use the index on X, find the matching rows, then sort by Y.
    There are cases where (1) would be fastest, because it has all of the columns from one scan (the other query plans will do random lookups on the primary for each row). This assumes that the data can fit into memory and the sort is fast.
    Query plan (2) will be fastest if the selectivity is moderate to high, looking up rows in the main table is fast, and sorting the rows is very slow for some reason (e.g., some complex collation).
    Query plan (3) will be fastest if the selectivity is small (only a small percentage of the rows in the table matches). This should be the best case for us, making it the best choice in a Berkeley DB key/value application.
    The optimal plan would result from having a composite index on (X, Y), which can return just the desired rows in the desired order. Of course, it does cost additional time and space to maintain that index. But note that you could have this index instead of a simple index on X: it can be used in any query the simple index could be used in.
    Records in Berkeley DB are (key, value) pairs. Berkeley DB supports only a few logical operations on records. They are:
    * Insert a record in a table.
    * Delete a record from a table.
    * Find a record in a table by looking up its key.
    * Update a record that has already been found.
    Notice that Berkeley DB never operates on the value part of a record. Values are simply payload, to be stored with keys and reliably delivered back to the application on demand. Both keys and values can be arbitrary byte strings, either fixed-length or variable-length.
    So, in case of a "SELECT * FROM X WHERE id=Y ORDER BY Z" query, our suggestion, from Berkeley DB's point of view, would be for you to use a composite index (as it would be in SQL), where a string created as X_Y should do the trick, as explained in the following scenario.
    Primary:
        X Y
    1 10 abc
    2 10 aab
    3 20 bbc
    4 10 bba
    5 20 bac
    6 30 cbaSecondary:
    10_aab 2
    10_abc 1
    10_bba 4
    20_bac 5
    20_bbc 3
    30_cba 6If the query looks like this:
    'SELECT * FROM primarydb WHERE X = 10 ORDER by Y'the application can run a cursor on the secondary and begin the loop with the DB_SET_RANGE flag on 10. When iterating with DB_NEXT, this will return:
    2 10 aab
    1 10 abc
    4 10 bbcThe application must check for the end of the range inside the loop, in this case it should stop when it hits 20_bac.
    As in SQL, retrieving by a secondary key is remarkably similar to retrieving by a primary key and the Berkeley DB call will look similar to its primary equivalent.
    tiplip wrote:
    Plus, do you have any suggestion about retrieval performance given the fact that topics retrieval will happen each time browser want to request the next page, that is, 2nd 25 topics of this forum?As you are concerned about the performance, I think this would be the fastest solution. Of course, you can tune the performance at a later time, after you have the functionality in place. What I think you should do first is to increase the cache size and test with a bigger database page size, and maybe to configure the transactional subsystem (in case you use one).
    If you are not very familiar with how to implement the above in BDB, please read the Guide to Oracle Berkeley DB for SQL Developers, available at: http://www.oracle.com/technetwork/articles/seltzer-berkeleydb-sql-086752.html
    You will also need to be familiar with the following documentation:
    Related documentation pages:
    Secondary indexes - http://download.oracle.com/docs/cd/E17076_01/html/programmer_reference/am_second.html
    Cursor operations - http://download.oracle.com/docs/cd/E17076_01/html/programmer_reference/am_cursor.html#am_curget
    DBcursor->get() - http://download.oracle.com/docs/cd/E17076_01/html/api_reference/C/dbcget.html
    DB_SET_RANGE - http://download.oracle.com/docs/cd/E17076_01/html/api_reference/C/dbcget.html#dbcget_DB_SET_RANGE
    If my answer helps you with your question, please go ahead and rate it as Helpful or Correct, and the forum thread as answered. For each unrelated question, please create a new forum thread.
    Good luck with building your forum application,
    Bogdan Coman
    PS: If you are a BDB licensed customer, you can also use My Oracle Support (https://support.oracle.com) to visit the KM note 1210173.1, that discusses the same topic.

  • How to create primary on a column when redundant data is present

    I am interested to add primary key constraint on a column where repeated data is there without affecting the date how can I immplement this.
    Can any one help me in this regard.
    Thanks
    Sanjay

    If you have duplicated data and going to specify the primary key constraint on that data it's quite against RDBMS concepts and can't be considered as a relevant idea. Nevertheless Oracle provides you with such tricky method, but once again, it's NOT good idea, change your mind:
    SQL> create table t (x int);
    Table created.
    SQL> insert into t values(1);
    1 row created.
    SQL> insert into t values(1);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select * from t;
             X
             1
             1
    SQL> create index t_x on t(x);
    Index created.
    SQL> alter table t add primary key (x) novalidate;
    Table altered.
    SQL> insert into t values(1);
    insert into t values(1)
    ERROR at line 1:
    ORA-00001: unique constraint (ORACLE_OCM.SYS_C006647) violated
    SQL> insert into t values(2);
    1 row created.
    SQL> select * from t;
             X
             1
             1
             2In this case you have PK constraint and it affects all new DMLs, but
    in fact you can't rely on PK.
    Rgds.

  • How to commit primary key in a multi level form

    Hi ,
    I am using Jdeveloper 10.1.2.3. ADF - Struts jsp application.
    I have an application that has multiple levels before it finally commits, say:
    Level 1 - enter name , address, etc details -- Master Table Employee
    Level 2 - Add Education details -- Detail Table Education
    Level 3 - Experience -- Detail Table Experience.
    Level 4 - adding a Approver -- Detail Table ApplicationApproval
    In all this from Level 1 I generate a document number which is the primary key that links all these tables.
    Now if User A starts Level 1 and moves to level 2,he gets document no = 100 and then User B starts Level 1 and also gets document no = 100 because no commit is executed.
    Now I have noticed that system crashes if User B calls a vo.validate().
    How can I handle this case as Doc no is the only primary key.

    Hi,
    This is what my department has been doing even before I joined and its been working for our multi user environment for these many years.
    We have a table called DOC_SRNO which will hold a row for our start docno , next number in running sequence. the final number. We have this procedure that returns next num to calling application and increments the next num by 1 in the table. and final commit on the application commits all this.
    I am not sure how this was working so far but each of those applications were for different employees. I am assuming this is how it worked.
    Now in the application that I am working on, has no distinct value. So two users could generate the same docno and proceed.
    I will try the DB sequence but here is what I tried. I call the next num from DOC_SRNO and I commit this table update and then proceed with this docno so at a time both gets different docno's.
    But my running session crashes when I go to next level to insert into the detail table of my multi level form. Here when I try to get the current row from the vo which is in context, it crashes.
    Here's the steps.
    Three tables : voMainTable1 and voDetailTable1 and voDetailTable2.
    voMainTable1 on create row1- I generate new docno - post changes
    voMainTable1 on create row2- I genrate another docno - post changes
    set voMainTable1 in context
    Now I call voDetailTable1 and to get the docno to join master detail, I try to get voMainTable1.getCurrentRow. Here it crashes.
    How can I avoid this

  • How to Register Primary Key in Apps

    Hi All,
    I have created parent & child relation n registered in Oracle Apps
    Now i have Primary keys in that tables,how can i register that columns in Apps Database.
    If any one knows u can forward to me itis urget
    Regards
    Siva

    please re-post the question in the e-business forum

  • How to create surrogate key in dimension without unique value

    Hi, I have a dimension where there is no column with unique value. I want to add a surrogate key to replace the existing primary key which is derived from concatenating 3 columns(e.g. 'A'||'B'||'C'). I'm thinking of using sequence. But this won't allow me to link the dimension to fact table. How do I come up with surrogate key under this situation? Thanks. ~Tracy

    I'm actually trying to accomplish something similar myself.
    In my sources I've got two sorts of customers, ones that are directly reported, and ones whose information is provided with sales records (this is stored in module ODS).
    Of course identification is different, but in the datamart (module DWH) I'm sort of forced to use an equivalent way of loading (due to the way it first used to work). To accelerate lookups on dimensions, I copy the ODS surrogate key to DWH dimensions, but this does not work for the 'inbuilt' customers because they do not have a surrogate key in the ODS.
    They DO have means of unique identification, and at first I thought I could concatenate these (also 3) columns to use as identification code. Unfortunately this is VARCHAR2, where the surrogate key is (naturally) NUMBER.
    So now it looks like I'm forced to first build a table in ODS especially for these 'inbuilt' customers and assign a surrogate key (by sequence) to it, this way it conforms to how 'normal' customers are loaded into DWH.
    I guess you'll have to pull of the same trick, i.e. create a table with either only the 'translation' of D-code to a surrogate key or all information that is fed into the dimension, which then can be used as a lookup or as complete source when loading data into your datamart.
    Good luck, Patrick

  • Creating primary key dynamically ?

    hi
    I have say table t1 which has pk constraint say pk1 using say 4 columns c1,c2,c3,c4 in database1.
    I need to create same pk constraint with same parameters and name on same table t1 which is into another database.
    I need a generic function / proc to do this as the tables can change and so as number of columns used in the primary key constraint .
    How do I go about this ?

    I need a generic function / proc If I may say so, this is completely the wrong way to manage change in the database. What you really need is a configuration management procedure that checks change scripts into a source control repository and makes sure they get run against all the affected databases.
    Cheers, APC

  • How to add primary key for table with existing data?

    The table is occupied data already. There was no primary key before, so for every column, there are some duplicate values.
    I want to add a new column, which should be of the datatype integer, and can automatically increment, starting from 001. I tried this in Oracle SQL Developer, but it says "ORA-01758: table must be empty to add mandatory (NOT NULL) column". How can I do it? Thanks!

    Hello, don't call the column ID, that could be an ID relating to anything. Perhaps be a little more specific like emp_id .
    Then to update it:
    UPDATE Employee emp
      SET emp_id = (
      SELECT row_num
        FROM (
      SELECT ROWID,
                 ROW_NUMBER() OVER (ORDER BY ROWID) row_num
        FROM Employee emp2) emp2
      WHERE emp.ROWID = emp2.ROWID);That will assign a new EMP_ID for each, beginning at 1.
    Then:
    ALTER TABLE Employee MODIFY emp_id NOT NULL;
    ALTER TABLE Employee ADD CONSTRAINT EMP_PK PRIMARY KEY (EMP_ID);Then create a sequence for future population of the Employee table:
    CREATE SEQUENCE emp_seq START WITH <maximum value of emp_id + 1>;

Maybe you are looking for