Primary Key Migration - Hierarchical Structures

Hi,
I'm involved in looking at a migration of a hierarchical database to ORACLE. For some table types the primary keys at the top of the hierarchy are compound ones and these need to be migrated to the next level of hierarchy. At the
next level of hierarchy there are further columns that need to become part of the primary key at that level.
Where the hierarchies get deep I'm looking at a pretty large primary key if this method is used.
Table A
Columns A1,A2
Primary Key A1,A2
Table B
Columns A1,A2,B1,B2
Primary Key A1,A2,B1,B2
Foreign Key referencing table A columns A1,A2
Table C
Columns A1,A2,B1,B2,C1,C2
Primary Key A1,A2,B1,B2,C1,C2
Foreign Key referencing table B columns A1,A2,B1,B2
To me this looks quite unwieldy so I was strongly considering giving tables A,B an C a new primary key 'ID'
column generated from a sequence and using that to maintain the relationships thus:
Table A
Columns ID,A1,A2
Primary Key ID
Unique Constraint A1,A2
Table B
Columns ID,A_ID,B1,B2
Primary Key ID
Unique Constraint A_ID,B1,B2
Foreign Key A references A column ID
Table C
Columns ID,B_ID,C1,C2
Primary Key ID
Unique Constraint B_ID,C1,C2
Foreign Key B_ID references B column ID
This involves another index for the ID column on each table I know, but it stops replication of data and would enable changes to the key values without losing the entire hierarchical relationship.
Does anyone have any experience with either of these two approaches who could shed some light on the pitfalls of each approach?
Thanks in advance
Mike

This seems to affect migrations from MS Access as well, so I guess it applies to all source db types. If it helps, PK's are created with SD 1.2.0 / 28.54, but not with 1.2.0 / 29.98.
As a related point it would be useful to show the constraint metadata in the captured and converted model info, rather than only see it as part of the gen script ?
Cheers
Jules

Similar Messages

  • 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

  • Missing Primary Key migration from mssql2000 to Oracle10

    I've been working with sql developer + migration workbench ver 1.1. There were some problems with it, but PK where created. sqldeveloper ver 1.2 migration from sql works quicker, but it misses PK creation.

    This seems to affect migrations from MS Access as well, so I guess it applies to all source db types. If it helps, PK's are created with SD 1.2.0 / 28.54, but not with 1.2.0 / 29.98.
    As a related point it would be useful to show the constraint metadata in the captured and converted model info, rather than only see it as part of the gen script ?
    Cheers
    Jules

  • How can we export the Primary key values (along with other data) from an Advantage database?

    One of our customers is moving from our application (which uses Advantage Database Server) to another application (which uses other database technology). They have asked us to help export their data, so that they can migrate it to another database system. So far, we have used the Advantage Data Architect (ARC32) "Export Table Structures as Code" functionality to generate SQL. We used the "Include existing data" option. The SQL contains the necessary code to recreate the tables and indexes. The customer's IT staff will alter the SQL statements as necessary for their new system.
    However, there is an issue with the Primary Keys in these table. The resulting INSERT statements use AutoInc as the type for the Primary Key in each Table. These INSERT statements contains "DEFAULT" for the value of each of these AutoInc fields. The customer would like to output an integer value for each of these Primary Key values in order to maintain referential integrity in their new system.
    So far, I have not found any feature of ARC32 that allows us to export the Primary Key values. We had been using an older version of ARC32, since our application does not use the latest version of ADS. I did download the latest version of ARC32 (11.10), but it does not appear to include any new functionality that would facilitate doing this sort of export.
    Can somebody tell me if there is such a feature in ARC32?
    Or, is there is another Advantage tool to facilitate what we are trying to accomplish?
    If there are no Advantage tools to provide such functionality, what else would you suggest?

    George,
      It sounds like the approach you are using is the correct one. This seems to be the cleanest solution to me especially since the customer is able to modify the generated SQL statements for their new system.
      In order to preserve the AutoInc values I would recommend altering the table and changing the field datatype from AutoInc to Integer. Then export the table as code which will export the actual values. After the tables have been created on the new system they can change the field datatype back to an AutoInc type if necessary.
    Regards,
    Chris Franz

  • Primary key violation when inserting records with insert_identity and ident_current+x

    My problem is this: I have data in a couple of temporary tables including
    relations (one table referencing records from another table by using
    temporary keys).
    Next, I would like to insert the data from the temp tables to my productive tables which have the same structure but their own identity keys. Hence, I need to translate the 'temporary' keys to regular identity keys in my productive tables.
    This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert
    data that way simultaneously.
    So far we were running the following solution, using a combination of
    identity_insert and ident_current:
    create table doc(id int identity primary key, number varchar(100))
    create table pos (id int identity primary key, docid int references doc(id), qty int)
    create table #doc(idx int, number varchar(100))
    create table #pos (docidx int, qty int)
    insert #doc select 1, 'D1'
    insert #doc select 2, 'D2'
    insert #pos select 1, 10
    insert #pos select 1, 12
    insert #pos select 2, 32
    insert #pos select 2, 9
    declare @docids table(ID int)
    set identity_insert doc on
    insert doc (id,number)
    output inserted.ID into @docids
    select ident_current('doc')+idx,number from #doc
    set identity_insert doc off
    -- Since scope_identity() is not reliable, we get the inserted identity values this way:
    declare @docID int = (select min(ID) from @docids)
    insert pos (docid,qty) select @docID+docidx-1, qty from #pos
    Since the request to ident_current() is located directly in the insert statement, we always have an implicit transaction which should be thread safe to a certain extend.
    We never had a problem with this solution for years until recently when we were running in occasional primary key violations. After some reasearch it turned out, that there were concurrent sessions trying to insert records in this way.
    Does anybody have an explanation for the primary key violations or an alternative solution for the problem?
    Thank you
    David

    >> My problem is this: I have data in a couple of temporary tables including relations (one table referencing records [sic] from another table by using temporary keys [sic]). <<
    NO, your problem is that you have no idea how RDBMS and SQL work. 
    1. Rows are not anything like records; this is a basic concept.
    2. Temp tables are how old magnetic tape file mimic scratch tapes. SQL programmers use CTEs, views, derived tables, etc. 
    3. Keys are a subset of attributes of an entity, fundamental characteristics of them! A key cannot be temporary by definition. 
    >> Next, I would like to insert the data from the temp tables to my production tables which have the same structure but their own IDENTITY keys. Hence, I need to translate the 'temporary' keys to regular IDENTITY keys in my productive tables. <<
    NO, you just get worse. IDENTITY is a 1970's Sybase/UNIX dialect, based on the sequential file structure used on 16-bit mini computers back then. It counts the physical insertion attempts (not even successes!) and has nothing to with a logical data model. This
    is a mag tape drive model of 1960's EDP, and not RDBMS.
    >> This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert data that way simultaneously. <<
    Gee, that is how magnetic tapes work, with queues. This is one of many reasons competent SQL programers do not use IDENTITY. 
    >> So far we were running the following solution, using a combination of IDENTITY_INSERT and IDENT_CURRENT: <<
    This is a kludge, not a solution. 
    There is no such thing as a generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. You have no idea what the ISO-11179 rules are. Even worse, your generic “id” changes names from table to table! By magic, it starts as a “Doc”,
    then becomes a “Pos” in the next table! Does it wind up as a “doc-id”? Can it become a automobile? A squid? Lady Gaga? 
    This is the first principle of any data model; it is based on the Law of Identity; remember that from Freshman Logic 101? A data element has one and only one name in a model. 
    And finally, you do not know the correct syntax for INSERT INTO, so you use the 1970's Sybase/UNIX dialect! The ANSI/ISO Standard uses a table consrtuctor: 
    INSERT INTO Doc VALUES (1, 'D1'), (2, 'D2'); 
    >> We never had a problem with this solution for years until recently when we were running in occasional PRIMARY KEY violations. After some research it turned out, that there were concurrent sessions trying to insert records [sic] in this way. <<
    “No matter how far you have gone down the wrong road, turn around.” -- Turkish proverb. 
    You have been mimicking a mag tape file system and have not written correct SQL. It has caught up with you in a way you can see. Throw out this garbage and do it right. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Primary key in BM&M layer

    Hi all,
    I'm using OBIEE 11g. I have a simple question - what's the point and meaning of the primary key for a dimension table in the BM&M layer? What is the purpose of it? I tried to change it whit different columns but no different effect. For hierarchical tables - i think there is a big difference, but in non- hierarchical?
    Thanks in advance,
    Alexander.

    Hi Srini,
    Thanks for quick reply.
    A logical level may have more than one level key. When that is the case, specify the key that is the primary key of that level. All dimension sources which have an aggregate content at a specified level need to contain the column that is the primary key of that level. Each logical level should have one level key that will be displayed when an Answers or Intelligence Dashboard user clicks to drill down. This may or may not be the primary key of the level. To set the level key to display, select the Use for drill down check box on the Level Key dialog box.What about the dimensions which doesn't have hierarchical structure - they aren't level-based or parent-child hierarchies? If i use them to just filter by them the fact tables?
    If i check the consistency i will receive an error that the dimension has to have a properly defined primary key.
    Thanks in advance,
    Alexander.

  • Primary keys on incorrect fields

    Hi. I am migrating a backend Access 97 database to Oracle 8.1.6.
    I have migrated the structure, but not data. I have noticed now that if I attach the new oracle tables to Access, even to a blank database, Access reports wrong columns as being the primary key. Yet, when I look at the entries for the primary keys in all_cons_columns they appear to be correct. Does anyone know how this would happen?
    Thanks,
    Ann Cantelow

    I have tried both the ODBC driver from the oracle client software, and the latest MDAC ODBC driver that Microsoft provides. The problem remains the same for each.
    These incorrect primary keys are on tables that have unique indexes- the attached table shows the first unique index as being the primary key. Remove all unique indexes, and the primary key is found correctly.
    Thanks,
    Ann Cantelow

  • UML to DB Diagram Transformation: Error with primary key in MySQL

    Hi,
    I am new in JDeveloper and I am following an Oracle tutorial to transform an UML class Diagram into a DB diagram http://docs.oracle.com/cd/E18941_01/tutorials/jdtut_11r2_81/jdtut_11r2_81_2.html.
    My idea is to create a real DB form this DB diagram.
    I am now trying to transform a simple UML class into a DB class. I want to use a MYSql transformation and I want to define my self primary key, so I done the following steps:
    - Create a UML class diagram
    - Create a class "Person" with an attribute "ID:String"
    - Define a Database profile
    - Define a stereotype in my primary key attribute where:
    + I have checked box "Is Primary Key?"
    + I set in property "Data Type MySql Database Server) to "Varchar(20) NOT NULL"
    Now when I try to do the transfromation:
    - I set option "UML to Offline Database Objects"
    - I create a new Offline DB which emulates a "MySQL Dataserver 5.x"
    - When I click "Finish" I become a popup error which says: "*Invalid name PERSON_PK. Must use `PRIMARY`for MYSQL Primary Key*"
    I don't really now how to solve this problem...I have tried all I have read and google but nothing works...I think I am forgotting something basic but I do not know what!
    I am working with JDeveloper 11.1.2.1.0 and with MySql Server 5.5.
    Thanks in advance!

    Result of that table issue fix is that migration went ahead, finished both uptime and downtime run. Now i am trying to login to SAP and system is unable to log me in as DOKTL doesnt exist at all
    But i see another table called DTELDOKTL in HANA, which same as DOKTL but no entries in it.
    I have created a message to SAP , But what should i be doing now ?
    Can i create this table in HANA ?
    Can i do export/import of table ? Table structure should be there in system already for this option i guess.
    Would i be able to replicate this table if i setup SLT ?
    Please advise
    C Mon Sep  8 11:02:30 2014
    C  *** ERROR =>   prepare() of C_0341, rc=1, rcSQL=259
    [dbsdbsql.cpp 1397]
    C  {root-id=00505680721D1EE48DE09241702FF193}_{conn-id=00000000000000000000000000000000}_0
    C  *** ERROR => PREPARE C_0341 on connection 0, rc=259
    [dbslsdb.cpp  9138]
    C  SQLCODE    : 259
    C  SQLERRTEXT : invalid table name:  Could not find table/view DOKTL in schema SAPECS: line 1 col 97 (at pos 96)
    C  sc_p=7f28f48cfac8,no=341,idc_p=7f28f3f87388,con=0,act=0,slen=254,smax=256,#vars=5,stmt=7a45980,table=DOKTL
    C  stmtid = <0/SAPMSYST                                /50334994/20140907170329>
    C  SELECT "ID" , "OBJECT" , "LANGU" , "TYP" , "DOKVERSION" , "LINE" , "DOKFORMAT" , "DOKTEXT" FROM "DOK\
    C  TL" WHERE "LANGU" = ? AND "ID" = ? AND "OBJECT" = ? AND "TYP" = ? AND "DOKVERSION" = ? ORDER BY "ID"\
    C   , "OBJECT" , "LANGU" , "TYP" , "DOKVERSION" , "LINE" ;
    B  ***LOG BZA=> table DOKTL does not exist on database R/3 [dbdbslst     3580]
    M  ThPerformDeleteThisSession: switch of statistics
    D  GuiStatus clear generate inline ts >20140908030105,195<
    M  ***LOG R47=> ThResFreeSession, delete () [thxxmode.c   1078]
    M  *** WARNING => ThrtGuiDeleteScreen: rscpGetUserLoginLang failed (128), use system language [thrtGuiHandl 469]
    Thanks,
    GR

  • Latest calculated Primary key item

    Hi ,
    I have table structure like below and i need to fetch latest calculated row item for each customer. I need OrderId(PKey) from below table.
    OrderID    CustomerId      DateCalculated
    1                   1                   1/1/2014
    2                    1                   2/1/2014
    3                     2                 4/1/2014
    4                     2                 5/1/2014
    5                     3                  5/1/2014.
    I need to fetch laste calculated row for each candidate
    OrderId             customerId            
    2                                 1
    4                                 2
    5                                 3
    i need orderId in the select list.
    Please provide the script for the same.
    Thanks in Advance

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules (you failed). Temporal
    data should use ISO-8601 formats (you failed). Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I have table structure like below  ..<<
    NO! There is no DDL, no structure shown. Now we have to guess and do your job for you. 
    >> .. and I need to fetch latest calculated row item for each customer. <<
    Google what a SEQUENCE is, if you do not know
    CREATE SEQUENCE Order_Seq
     AS INTEGER
     START WITH 1
     INCREMENT BY 1
     MINVALUE 1
     MAXVALUE 999999
     NO CYCLE; 
    CREATE TABLE Orders
    (order_seq INTEGER DEFAULT NEXT VALUE FOR Order_Seq 
     PRIMARY KEY,
     customer_id INTEGER NOT NULL
       REFERENCES Customers(customer_id),
     order_date DATE DEFAULT CURRENT_TIMESTAMP NOT NULL);
    INSERT INTO Orders (customer_id, order_date)
    VALUES
    (1, '2014-01-01'),
    (1, '2014-01-02'),
    (2, '2014-01-04'),
    (2, '2014-01-05'),
    (3, '2014-01-05');
    >> I need to fetch last calculated row for each candidate <<
    CREATE VIEW Recent_Orders (recent_order_seq, customer_id)
    AS
    SELECT MAX(order_seq), customer_id 
      FROM Orders
     GROUP BY  customer_id;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to create one primary key for each vendor

    Hi all
    i am doing IDOC to jdbc scenario
    i am triggering idoc from R/3 and the data is going into DB table vendor through XI.
    structures are as follows:
    sender side: ZVendorIdoc (this is a customized IDOC , if i triger IDOC for multiple vendors then it triggers only 1 idoc with multiple segment )
    Receiver side:
    DT_testVendor
        Table
            tblVendor
                action UPDATE_INSERT
                access                     1:unbounded
                    cVendorName         1
                    cVendorCode        1
                    fromdate                1
                    todate                    1
                 Key1
                    cVendorName         1
    if i trigger idoc for multiple vendors ,for example vendor 2005,2006 and 2010 . then i can see that the only key comes from the very first field (2005) and the whole record for vendor 2005,2006 and 2010  goes into the table with this(2005) as a primary key
    now again if i send data for these three vendor 2005, 2006 , 2010, in which record for the vendor 2005 is same and for 2006 and 2010 are different than it takes 2005 as a primary key and it does not update the data in the table.
    my requirement is like this:   for each vendor there should be one unique key assigned.
                                              for above said example there should come three keys one for each vendor .
    could you please help me how to do this???????????

    Hi,
      In Mapping Make the statement is 0-unbounded.For each vendor create a statement.This will solve your problem.
    Regards,
    Prakasu.M

  • Difference between primary key and primary index

    Dear All,
             Hi... .Could you pls tell me the difference between primary key and primary index.
    Thanks...

    Hi,
    Primary Key : It is one which makes an entry of the field unique.No two distinct rows in a table can have the same value (or combination of values) in those columns.
    Eg: first entry is 111, if you again enter value 111 , it doesnot allow 111 again. similarly for the strings or characters or numc etc. Remember that for char or numc or string 'NAME' is not equal to 'name'.
    Primary Index: this is related to the performance .A database index is a data structure that improves the speed of operations in a table. Indices can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records. The disk space required to store the index is typically less than the storage of the table (since indices usually contain only the key-fields according to which the table is to be arranged, and excludes all the other details in the table), yielding the possibility to store indices into memory from tables that would not fit into it. In a relational database an index is a copy of part of a table. Some databases extend the power of indexing by allowing indices to be created on functions or expressions. For example, an index could be created on upper(last_name), which would only store the uppercase versions of the last_name field in the index.
    In a database , we may have a large number of records. At the time of retrieving data from the database based on a condition , it is a burden to the db server. so whenever we create a primary key , a primary index is automatically created by the system.
    If you want to maintain indices on other fields which are frequently used in where condition then you can create secondary indices.
    Reward points if helpful.
    Thanks,
    Sirisha..

  • How do I create an Entity Bean with unknown primary keys

    Hi,
    Can a good folk help me.
    I am mapping an entity bean to an oracle table for the purpose of logging . I do not need a primary key contraint on this table. How do I specify in my entity bean file descriptor not to use any field for primary key ...
    I have done this so far...
    in my ejb.xml file - I set....
    <prim-key-class>java.lang.Object</prim-key-class>
    and deleted ....
    <primkey-field>...</primkey-field>
    My table structure is .....
    CREATE TABLE FAMS_REQUEST_LOG (
    EDITEDBY VARCHAR2(20),
    OLDTRANSDATE DATE,
    REQUESTID VARCHAR2(30) NOT NULL,
    OLDQTY NUMBER(20),
    NEWQTY NUMBER(20),
    NEWTRANSDATE DATE)
    but I still get this error message on deploying...
    [#|2006-03-01T14:30:29.250+0100|INFO|sun-appserver-pe8.1_02|javax.enterprise.system.tools.deployment|_ThreadID=19;|Total Deployment Time: 11000 msec, Total EJB Compiler Module Time: 0 msec, Portion spent EJB Compiling: 0%|#]
    [#|2006-03-01T14:30:29.265+0100|SEVERE|sun-appserver-pe8.1_02|javax.enterprise.system.tools.deployment|_ThreadID=19;|Exception occured in J2EEC Phase
    com.sun.enterprise.deployment.backend.IASDeploymentException: Fatal Error from EJB Compiler -- JDO74046: JDOCodeGenerator: Caught a MappingConversionException loading or creating mapping model for application 'fixassetenterpriseapp' module 'FixAssetEnterpriseApp-EJBModule': JDO71030: There is no column in table FAMS_REQUEST_LOG which can be used to support the servers implementation of unknown key classes.
    at com.sun.ejb.codegen.CmpCompiler.compile(CmpCompiler.java:274)
    at com.sun.ejb.codegen.IASEJBC.doCompile(IASEJBC.java:615)
    at com.sun.ejb.codegen.IASEJBC.ejbc(IASEJBC.java:563)
    at com.sun.enterprise.deployment.backend.EJBCompiler.preDeployApp(EJBCompiler.java:340)
    at com.sun.enterprise.deployment.backend.EJBCompiler.compile(EJBCompiler.java:209)
    at com.sun.enterprise.deployment.backend.AppDeployer.runEJBC(AppDeployer.java:284)
    at com.sun.enterprise.deployment.backend.AppDeployer.deploy(AppDeployer.java:176)
    at com.sun.enterprise.deployment.backend.AppDeployer.doRequestFinish(AppDeployer.java:107)
    at com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:146)
    at com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:71)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:633)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:188)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:520)
    at com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:143)
    at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:172)
    |#]
    Dotun

    you will have to create a sequence and a trigger
    CREATE SEQUENCE <SEQUENCE NAME>
    INCREMENT BY  1
    START WITH  1
    NOCACHE
    /this sequence will guarantee that each requested number is unique
    the trigger will select from this sequence and insert the obtained value in the new record
    CREATE OR REPLACE TRIGGER <TRIGGER NAME>
    BEFORE INSERT ON <TABLE NAME>
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
        BEGIN
            select
                <SEQUENCE NAME>.nextval
            into
                :NEW.<COLUMN NAME>
            from
                dual;
        END;
    [/CODE]
    this will always take the value from the sequence, even if you already provided a value yourself
    (otherwise you will first have to test if :NEW.<column name> is null, but I wouldn't do this for a key column.
    if you need the generated key back for further processing (inserting it into a child table for example), you can use the returning clause on the insert statement
    see the oracle documentation for more information about sequences, triggers and the returning clause
    greetings
    Freek D
    I am new to Oracle and need to know how to create a table that uses an automatic incrementation on a primay key for it's default. I need the uniqueness automatically managed by the DBMS.. This activity is know as setting the Column (primary key with identity) in Ms-SQL..
    Your help would be appreciated greatly....
    Thanks....

  • Having a problem with creating/using a primary key on a view

    I have a problem with a primary key on a view
    I created the view and primary key as follows:
    CREATE OR REPLACE FORCE VIEW "MDD"."ROCK_LU" ("DESCRIPTION",
         UNIQUE ("DESCRIPTION") RELY DISABLE,
         CONSTRAINT "ROCK_LU_PK" PRIMARY KEY ("DESCRIPTION") RELY DISABLE) AS
    SELECT DESCRIPTION
    FROM MRMC_LU
    WHERE ROCK = 'T';
    The view with the primary key appears to have been created as there were no error messages. (The above was from the sql tab in sql developer.)
    When I try to create the foreign key on my mdd_hr table - I get an error
    /* hr_name - foreign key */
    ALTER TABLE mdd_hr add CONSTRAINT hr_name_fk FOREIGN KEY (hr_name) REFERENCES rock_lu(description);
    Error report:
    SQL Error: ORA-02270: no matching unique or primary key for this column-list.
    When I lookup the index in sql developer, rock_lu_pk is not there.
    All my other foreign keys work - but I don't understand what I am doing wrong with this one. Please help.
    glenn
    Background - as to why I want to use a view as a lookup table.
    The MRMC_LU table that the view is created from is structured like:
    DESCRIPTION - MINERAL - ROCK - MODIFIER - COMMODITY
    ANHYDRITE - T - T - T
    APLITE - T - - T
    GRAPHITE - T - - - T
    GREYWACKE - - T
    DESCRIPTION is a list of all names of minerals, rocks, modifiers and commodities. T is entered in each valid field. Often a description name is used for both a mineral and a rock or a mineral and a commodity or any other combination. Because this database is just starting up, it was more efficient to create one table that could be updated (and thereby automatically update the MINERAL_LU, ROCK_LU, MODIFIER_LY, COMMODITY_LU views) rather than create and maintain four separate but similar tables. A primary key cannot be generated for the MRMC_LU table as there are nulls in each column
    except DESCRIPTION.
    Perhaps there is a smarter way to do this?

    http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/statements_85a.htm#2065512
    You can specify constraints on views and object views. You define the constraint at the view level using the out_of_line_constraint clause. You define the constraint as part of column or attribute specification using the inline_constraint clause after the appropriate alias.
    Oracle does not enforce view constraints. However, operations on views are subject to the integrity constraints defined on the underlying base tables. This means that you can enforce constraints on views through constraints on base tables.
    Restrictions on View Constraints
    View constraints are a subset of table constraints and are subject to the following restrictions:
    You can specify only unique, primary key, and foreign key constraints on views. However, you can define the view using the WITH CHECK OPTION clause, which is equivalent to specifying a check constraint for the view.
    Because view constraints are not enforced directly, you cannot specify INITIALLY DEFERRED or DEFERRABLE.
    View constraints are supported only in DISABLE NOVALIDATE mode. You must specify the keywords DISABLE NOVALIDATE when you declare the view constraint, and you cannot specify any other mode.
    You cannot specify the using_index_clause, the exceptions_clause clause, or the ON DELETE clause of the references_clause.
    You cannot define view constraints on attributes of an object column.
    Rgds.

  • View Objects with Union Queries--trouble with primary keys

    Hi,
    I'm working with JDev 11.1.1.3 and am trying to do a couple of things (without success--yet). I am trying to create a master-detail relationship that displays the existing data in a set of 3 tables and later I will be creating forms for inserting and updating.
    The table structure is like this:
    Table: Member
    Field: MemberIdx (PK)
    Field: Data
    Table: CfgPartner
    Field: MemberIdx (PK)
    Field: DocType (PK)
    Field: DocRevision (PK)
    Field: OtherData
    Table: CfgB2BPartner
    Field: MemberIdx (PK)
    Field: DocType (PK)
    Field: DocRevision (PK)
    Field: B2BData
    I have a View Object for the master table (Member). And I have created a 2nd View Object that is a union of the other two tables. There is some data in CfgPartner that doesn't have a matching record in CfgB2BPartner and vice versa. My thinking is that the two tables are related and I would like them to display within the same table on the ADF page.
    My 2nd View Object has this query:
    SELECT CfgPartner.MEMBERIDX,
    CfgPartner.DOCTYPE,
    CfgPartner.DOCREVISION,
    CfgPartner.OTHERDATA,
    CfgB2bpartner.B2BDATA
    FROM CFG_PARTNER CfgPartner, CFG_B2BPARTNER CfgB2bpartner
    WHERE CfgPartner.MEMBERIDX=CfgB2bpartner.MEMBERIDX(+)
    and CfgPartner.DOCTYPE=CfgB2bpartner.DOCTYPE(+)
    and CfgPartner.DOCREVISION=CfgB2bpartner.DOCREVISION(+)
    UNION
    SELECT CfgB2bpartner.MEMBERIDX AS MEMBERIDX1,
    CfgB2bpartner.DOCTYPE AS DOCTYPE1,
    CfgB2bpartner.DOCREVISION AS DOCREVISION1,
    CfgPartner.OTHERDATA,
    CfgB2bpartner.B2BDATA
    FROM CFG_PARTNER CfgPartner, CFG_B2BPARTNER CfgB2bpartner
    WHERE CfgB2bpartner.MEMBERIDX=CfgPartner.MEMBERIDX(+)
    and CfgB2bpartner.DOCTYPE=CfgPartner.DOCTYPE(+)
    and CfgB2bpartner.DOCREVISION=CfgPartner.DOCREVISION(+)
    ORDER BY MEMBERIDX,DOCTYPE,DOCREVISION
    The query is valid and runs fine in the database. However, the error I'm getting in the app module makes it sound like I don't have my primary keys set up correctly. Here is the error: (oracle.jbo.PersistenceException) JBO-26028: View object testCfgPtnrCfgB2BPtnr does not include a primary key attribute Memberidx of entity base CfgB2bpartner.
    In the View Object it shows the attributes Memberidx, Doctype, Docrevision, Memberidx1, Doctype1, and Docrevision1 all as key attributes. The only strange thing I see is the Entity Usage for Memberidx1, Doctype1, and Docrevision1 are all empty and the info column says "Transient".
    Any help would be appreciated.
    -Steve

    Hi,
    I think that to achieve this you need to suround it with another "select from" statement and create alias for the columns
    I created a test with the departments table (assuming that they are two different tables with different attributes) just to see that it works.
    SELECT DEPID1,DEPID2,DEPNAME1,DEPNAME2
    FROM(
    SELECT Departments1.DEPARTMENT_ID AS DEPID1,
               NULL as DEPID2,
           Departments1.DEPARTMENT_NAME AS DEPNAME1,
              NULL as DEPNAME2
    FROM DEPARTMENTS Departments1
    UNION
    SELECT Departments2.DEPARTMENT_ID AS DEPID2,
              NULL as DEPID1,
           Departments2.DEPARTMENT_NAME AS DEPNAME2,
             NULL as DEPNAME1
    FROM DEPARTMENTS Departments2)The resulting VO will have 4 attributes and you can set the primary key to be (DEPID1,DEPID2)
    If your 2 tables have common columns then these columns can have the same alias
    If you have any problems let me know :)
    Gabriel.

  • Primary Key rule Violation error while Insert Record in Compact DB

    Hi All,
    I have One Table in Server Name "Student"  when i Synchronize this with the help of Microsoft Synchronization Framework
    same Table schema with Data has been create in CompactDataBase.
    When i insert data in CompactDataDase it give me Primary Key Violation error.
    Please Suggest
    Example
    Table Structure is as Follows:-
    Create Table Student(
    [Emp_id] int IDENTITY(1,1) NotNull,[Emp_Name] int NOTNULL );insert into Student Values('John');insert into Student Values('Joe');Thanks & RegardsNamit Jain

    try this and see if it solves,
    also, Emp_name data type is int. it should be varchar.
    I suspect the reason is because you already have some data in student table but you identity seeds were not updated and hence it is trying to insert a row with emp_id value that already exists.and hence the primary key violation. also, your table DDL did
    not really have an primary key but it would still error since you are inserting duplicate row in the identity column.
    so, try resetting the identity seed value to the max(emp_id) in the table.
    select max(Emp_ID) from  student
    --use the output of the above statement
    DBCC CHECKIDENT ('Student', RESEED,<<--use the output of the above statement-->>)
    --your max(emp_id) should match with last_value column in the below( do not if this query would run in compact DB though)
    select seed_value,increment_value,last_value from sys.identity_columns where object_id=object_id('Student')
    now, try your insert.
    Hope it Helps!!

Maybe you are looking for

  • Steve Jobs' iMac Keynote Address Video

    Is there an URL for the video of Steve Jobs unveiling the new iMac and iLife 08? I had seen it before but the link to the video is gone and is now replaced by the new iPod unveiling. I would really like to watch that video again.

  • Systemd-backlight using intel_backlight?

    Hi, The backlight on my new laptop is controlled by values inside the intel_backlight directory (/sys/class/backlight/intel_backlight) however the systemd-backlight service (which saves the current backlight settings at shutdown and restores them at

  • How can I upgrade free subscription WebBasic site to paid eCommerce site?

    Hi, How do I upgrade a free cloud subscription WebBasic site to a paid eCommerce site? The only solution I could find in the forum was to replicate the site under the Premium Partner feature. Surely there must be an easier way than this, especially f

  • Don't understand Error code

    I was reading a specific channel on a 6025E using the test of the card, i had this error code ;Possible reasons: NI-DAQ LV: A channel, port, or counter is out of range for the device type or device configuration; or the combination of channels is not

  • While Browsing Infoview in IE11 in sap bo 3.1 sp3

    Hi Exports , we are using sap bo 3.1 sp3 ...Recently we installed   IE11 in my system .Is it support ?.when i am opening Infow in IE 11 .Iam facing below error Image 1: While Editing Image 2: While refreshing Image 3: While scheduling Thanks, Raghuna