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

Similar Messages

  • 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

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

  • SQL Data Modeler 3.0 EA1 trying to create primary key on OT

    Hi,
    I'm trying to modify a primary key of an object table that was reversed (imported) from an Oracle 11.2.x RDBMS and am getting the error message "Incomplete Index definition". It is showing in the window "Index Columns Assignment". I get to the 'Primary Key Properties' window by pressing the 'Properties' button on the 'Table Properties' -> 'Primary Key'. If I try to edit the expression and then press the Ok or Apply buttons I get the error. With this be fixed in the production version? Will we be able to create a model in SQL Developer Data Modeler that generates a SQL statement similar to the following:
    ALTER TABLE x_flags
    ADD (CONSTRAINT x_flags_pk PRIMARY KEY (flags.id))
    Thanks,
    Scott K

    Hi Scott,
    I'm trying to modify a primary key of an object table that was reversed (imported) from an Oracle 11.2.x RDBMS and am getting the error message "Incomplete Index definition"... With this be fixed in the production version?yes
    Will we be able to create a model in SQL Developer Data Modeler that generates a SQL statement similar to the following:
    ALTER TABLE x_flags
    ADD (CONSTRAINT x_flags_pk PRIMARY KEY (flags.id))I assume "flags" is column of object type and "id" is attribute of that type. I logged bug for that, so there will be support however not for 3.0.
    Philip

  • Create Primary key on View?

    Hi
    Can we create a Primary or Unique key on a simple view? while actual table doesn't have any primary or unique key
    Regards,
    Nasir.

    But what about this Example.
    CREATE VIEW emp_sal (emp_id, last_name,
    email UNIQUE RELY DISABLE NOVALIDATE,
    STRAINT id_pk PRIMARY KEY (emp_id) RELY DISABLE
    NOVALIDATE)
    AS SELECT employee_id, last_name, email FROM
    employees;This creates a view and tells Oracle that the optimizer is free to rely on email and emp_id being unique but that your code will enforce both constraints. Since you know that your data violates these constraints, that basically means that you're lying to the optimizer and allowing it to make incorrect assumptions about the data. That, in turn, permits the optimizer to either generate incorrect query plans or deliver you incorrect data should it happen to rely incorrectly on one of these constraints. Realistically, this sort of view would take an existing data quality issue and layer on a bunch of optimizer issues rather than addressing the root cause and fixing the data.
    Justin

  • MSSQL2000 to 8i hangs on Create Primary Keys

    I am trying to create the repository on an Oracle 8i DB coming from SQL Server 2000. The process runs fine for awhile, but when it gets to where it is done creating the info for primary keys it hangs and I have to cancel the process. Any ideas on what to check?

    Problem seems to be related to having dbo as the table owner. The product was not able to write the table info with dba as the owner. Once I changed this to something else, it worked fine.

  • Creating Primary Key Index

    Hi,
    Iam trying to create a Primary Index on Large table and Iam using the Parallelism to make it fast. I have used the following script to create a Primary key Index.
    CREATE UNIQUE INDEX FLX_ARCH.FUND_SEC_RESULT_STAT_ARCH_PK
    ON FLX_ARCH.FUND_SEC_RESULT_STAT_ARCH
    (FUND_SEC_RESULT_MAP_INST,RATES_RULE_ID,BASE_LOCAL_FLAG,EFFECTIVE_DATE)
    TABLESPACE FLX_PERF_I
    parallel;
    Index created.
    Elapsed: 01:43:37.37
    Index got created in 1 hour 43 minutes. But when Iam adding constarint to those columns, it is taking almost 12hours with or without parallelism.
    ALTER TABLE FLX_ARCH.FUND_SEC_RESULT_STAT_ARCH
    ADD CONSTRAINT FUND_SEC_RESULT_STAT_ARCH_PK
    PRIMARY KEY
    (FUND_SEC_RESULT_MAP_INST,RATES_RULE_ID,BASE_LOCAL_FLAG,EFFECTIVE_DATE)
    parallel
    Would you please let me know what could be the problem and how can we add the Primary constraint fast.
    Your early response is much appreciated.
    Thanks and Regards
    Suresh. D

    Would you please let me know what could be the problem and You have presented no details that indicate any problem exists.
    how can we add the Primary constraint fast. Fast is relative.
    If I asked you to make my snail fast, could you do so?
    ALTER SESSION SET SQL_TRACE=TRUE;
    ALTER TABLE FLX_ARCH.FUND_SEC_RESULT_STAT_ARCH
    ADD CONSTRAINT FUND_SEC_RESULT_STAT_ARCH_PK
    PRIMARY KEY
    (FUND_SEC_RESULT_MAP_INST,RATES_RULE_ID,BASE_LOCAL_FLAG,EFFECTIVE_DATE)
    parallel
    ALTER SESSION SET SQL_TRACE=FALSE;
    now find the trace file within ./udump folder
    tkprof <trace_file.trc> trace_results.txt explain=<username>/<password>
    By inspecting the trace file you will be able to see where time is being spent.
    With this knowledge, you may or may not be able to determine the bottleneck & therefore improve it

  • Creating Primary key Index as Local Partitioned Index.

    CREATE TABLE T1(
    x NUMBER,
    y NUMBER
    )PARTITION BY LIST(x)
    PARTITION P1 VALUES (1),
    PARTITION P2 VALUES (2),
    PARTITION Pmax VALUES (default)
    ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY(Y) LOCAL;
    Error starting at line 1 in command:
    ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY(Y) LOCAL
    Error report:
    SQL Error: ORA-01735: invalid ALTER TABLE option
    01735. 00000 - "invalid ALTER TABLE option"
    *Cause:   
    *Action:
    Can you please help me how to achieve this in Oracle 10g R2?

    LOCAL keyword is invalid with ALTER TABLEDepends:
    SQL>  create table t1 (x number, y number)
    partition by list (x)
       (partition p1
           values (1),
        partition p2
           values (2),
        partition pmax
           values (default))
    Table created.
    SQL>  alter table t1 add constraint t1_pk primary key(x, y) using index local
    Table altered.

  • Creating primary key constraint

    hi,
    if i have a table created, and i inserted say around 10 records ( there are no primary key or any other constraints ) , after inserting those 10 records now can i create a primary key constraint with enable novalidate option ?
    thanks

    No, you can create a PK Constraint which is initially disabled:
    alter table t add constraint t_pk primary key(owner) disable;But when you try:
    alter table t enable novalidate constraint t_pk;You will get a ORA-02437 Error if there are duplicat values (Oracle 10g).
    Dim

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

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

  • Unable to create primary key

    Hi all.
    This one I can't handle. Do you guys know where I can find this constraint?
    SQL> desc marcos
    Name                                      Null?    Type
    COD                                                VARCHAR2(40)
    DSC                                                VARCHAR2(30)
    SQL> select * from marcos;
    COD                                      DSC
    1                                        adfasdfas
    2                                        asdfasfdas
    3                                        asfasklfjd
    1                                        safasjfasdf
    SQL> alter table marcos
      2  add (constraint pk_marcos primary key(cod))
      3  /
    alter table marcos
    ERROR at line 1:
    ORA-01408: such column list already indexed
    SQL> select * from user_cons_columns
      2  where upper(table_name) like '%MARCOS%'
      3  /
    no rows selectedTIA
    Marcos

    Even you don't have bitmap index on it the query will still fail, you had duplicate record in this column :)
    COD DSC
    1 adfasdfas
    2 asdfasfdas
    3 asfasklfjd
    1 << safasjfasdf

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Primary Keys and ADT

    Hi,
    For uniformity sake, I've created a new data type with one property in it (VARCHAR2(30)). Prior to this I had that data type in all of my tables and created primary keys on that. Now, I have replaced the old VARCHAR2(30) with this new data type YET I want to keep my primary key on it. When I do this I get an error indicating a primary key can NOT be on a user defined data type.
    Am I missing something? Should I post code? Is this not possible?
    Any advice would be GREATLY appreciated.

    Steve,
    Primary key columns cannot be an object type.
    Regards,
    Geoff

  • Problem with foreign and primary keys migration from SQL Server to Oracle

    Hi folks, i'm using SQL Developer to migrate from a SQL Server database to Oracle and i'm stuck with a couple issues:
    The worst of them so far is the fact that i can't migrate any of the PKs and FKs. After successfully capturing the SQL Server DB model and converting it to Oracle, when the tool generates the scripts, all ALTER TABLE queries that add the PKs and FKs have their target columns duplicated.
    for example: when i'm trying to migrate a simple table that contains an Id (PK) and Name columns, the tool generates the following scripts:
    PROMPT Creating Table TestTable...
    CREATE TABLE TestTable (
    Id NUMBER(10,0) NOT NULL,
    Name VARCHAR2 NOT NULL
    PROMPT Creating Primary Key Constraint PK_TestTable on table TestTable ...
    ALTER TABLE TestTable
    ADD CONSTRAINT PK_TestTable PRIMARY KEY
    Id,
    Id
    ENABLE
    As for the FKs, the tool duplicates the columns as well:
    ALTER TABLE SomeTable
    ADD CONSTRAINT FK_SomeTable_SomeTable2 FOREIGN KEY
    SomeTable2Id,
    SomeTable2Id
    REFERENCES SomeTable2
    Id,
    Id
    ENABLE
    Does anyone have a clue on how to solve these issues? I'd be greatly thankful for any answers!

    Hi Fernando,
    I was unable to replicate this issue. My primary / foreign keys where defined using unique columns.
    PROMPT Creating Primary Key Constraint PK_Suppliers on table Suppliers ...
    ALTER TABLE Suppliers
    ADD CONSTRAINT PK_Suppliers PRIMARY KEY
    SupplierID
    ENABLE
    I tried a few things like
    capturing twice and renaming both models the same
    renaming the converted models
    but with no luck.
    I think this issue is occuring either at the capture or convert phase.
    1) Are you performing the capture online or offline?
    2) Can you provide a the entire DDL for one of these tables and its indexes to see if I can replicate?
    3) Did the capture or convert fail or have to be redone at any stage ?
    I all else fails I would attempt a capture and convert again using a brand new repository (create a new schema in Oracle and associate the migration repository with it).
    Regards,
    Dermot
    SQL Developer Team
    Edited by: Dermot ONeill on Oct 22, 2009 12:18 PM

Maybe you are looking for