Question of design on unique constraints while moving to multi-tenant

Hi all

Please see the definition of this simple table:
CREATE TABLE emp 
    ( 
     id INTEGER  NOT NULL , 
     name VARCHAR2 (30 CHAR)  NOT NULL , 
     birthdate DATE  NOT NULL , 
     username VARCHAR2 (10 CHAR) ,
     CONSTRAINT PK_ PRIMARY KEY ( id ) ,
     CONSTRAINT UC_emp_username UNIQUE ( username )
    );
In this framework, each user can (not essential, authorized NULL) have a user name. A user name can only be used once. An application that uses this type of table is not multi-tenant capable.

Now if I run the application of several tenants, I add a column tenant_id like this:
CREATE TABLE emp 
    ( 
     id INTEGER  NOT NULL , 
     name VARCHAR2 (30 CHAR)  NOT NULL , 
     birthdate DATE  NOT NULL , 
     username VARCHAR2 (10 CHAR) ,
     tenant_id INTEGER  NOT NULL ,
     CONSTRAINT PK_ PRIMARY KEY ( id ) ,
     CONSTRAINT UC_emp_tenant_username UNIQUE ( tenant_id, username )
    );
I have archived almost my goal:
However, a user can (not essential, authorized NULL) have a user name. A user name cannot be used once BY the TENANT (see changed CPU). Of course, each tenant must be provided with an account named 'administrator', so the CPU must include the tenant_id. But what does not work:

As soon as I add a 2nd employee for a tenant and this user doesn't have a login name (and therefore no user name), the UC has banned the addition of this user.
It was no problem in the 1st case, because the CPU included a single column and a row in the base table with a NULL value in this column is simply ignored in the index.
In the 2nd case, each row in the base table is included in the CPU, because the tenant_id column is NOT NULL. If the combination {tenant_id:1, username: NULL} cannot exist only once. This means that almost all employees must have a user name.

What is the solution here?
Drop the CPU is not a solution.
Is it really necessary to move the user name column to a new table, as in the following? It just doesn't feel good to introduce a table of relationship for a 1:1 relationship.
CREATE TABLE emp 
    ( 
     id INTEGER  NOT NULL , 
     name VARCHAR2 (30 CHAR)  NOT NULL , 
     birthdate DATE  NOT NULL , 
     tenant_id INTEGER  NOT NULL ,
     CONSTRAINT PK_emp PRIMARY KEY ( id )
    ) ;

CREATE TABLE username 
    ( 
     id INTEGER  NOT NULL , 
     emp_id INTEGER  NOT NULL , 
     username VARCHAR2 (30 CHAR)  NOT NULL , 
     tenant_id INTEGER  NOT NULL ,
     CONSTRAINT PK_username PRIMARY KEY ( id ) ,
     CONSTRAINT UC_username_emp UNIQUE ( emp_id ) ,
     CONSTRAINT UC_username_username_tenant UNIQUE ( username , tenant_id ) ,
     CONSTRAINT FK_username_emp FOREIGN KEY ( emp_id ) REFERENCES emp ( id ) 
    ) 
;
Any ideas or links to books that are greatly appreciated.

Thank you
Blama

Hi, Lawrence.

Sorry, I'm not sure you understand the problem. It would be useful that you posted some INSERT statements that should be allowed, and some that must fail because they violate the rule of oneness. Or by post at least a scneario of business that you might neeed to model. For example "tenant 1 has 3 employees: 11, 12 and 13." Employee 11A username "FFL". 12 has no username. 13 should be able to choose any username except "Elf", or not having a (just like the 12). 2 a 2 employees... »

You can create an index based on a single function. For example, if the user name is optional:

CREATE UNIQUE INDEX emp_name_unique ON
username ( NVL2 (username, tenant_id, NULL)
         , username
         );

If username is NULL, then the two expressions of the index will be NULL and no index entry will be. So there may be a number any lines with the same tenant_id, but no user name, but only one line for each (tenant_id, username) combination when there is a user name.

Laurent wrote:
... Is it really necessary to move the user name column to a new table, as in the following? It just doesn't feel good to introduce a table of relationship for a 1:1 relationship.

Good instinct; It's weird (but not necessarily bad) to have a one-to-one relationship between the tables, but do you? When you say things like

... A user name cannot be used once a TENANT...

or

... As soon as I add a 2nd employee for a tenant...

Looks like you have a one-to-many relationship, or maybe a many-to-many relationship, or maybe even two relationships, neither of which is unequivocal.

Published by: Frank Kulash, October 26, 2012 09:15

Tags: Database

Similar Questions

  • Question of the unique constraint with finance charge

    Hi friends,

    As part of the implementation of 11 g BIAPPS-ODI during the execution of a finance charge is my load of CM plan failed with the error like below

    ODI-1519: series step 'Load start Plan (InternalID:1242500)' failed because step 'Refresh Global Variable (InternalID:1243500)' child is in error.

    ODI-1519: series step 'Refresh Global Variable (InternalID:1243500)' failed because the step child "Warehouse loading Phase (InternalID:2336500)" is a mistake.

    ODI-1519: series step "Warehouse loading Phase (InternalID:2336500)" failed because the child step "SIL 1 charge (InternalID:2337500)" is a mistake.

    ODI-1519: series step '1 SIL Load (InternalID:2337500)' failed, because the child step '2 group of dimensions of SIL (InternalID:2338500)' is a mistake.

    ODI-1519: series step '2 group of dimensions of SIL (InternalID:2338500)' failed because the child step "Parallels - independent DimGroup (InternalID:2346500)" is a mistake.

    ODI-1518: parallel step 'Parallels - independent DimGroup (InternalID:2346500)' failed. level of 1 child by mistake, which is more than the maximum number of allowed errors (0) defined for parallel step.  Has no measures of the child: 3 SIL Dims POSHIER_DIM (InternalID:2369500)

    ODI-1519: series step '3 SIL Dims POSHIER_DIM (InternalID:2369500)' failed because the child "POSHIER_DIM (InternalID:2372500)" is a mistake.

    ODI-1519: series step "POSHIER_DIM (InternalID:2372500)" failed because step "SIL_PositionDimensionHierarchy (InternalID:2377500)" child is in error.

    ODI-1217: SILOS_SIL_POSITIONDIMENSIONHIERARCHY Session (4278500) fails with return code 1.

    ODI-1226: SIL_PositionDimensionHierarchy.W_POSITION_DH step fails after 1 attempt.

    ODI-1240: Flow Run SIL_PositionDimensionHierarchy.W_POSITION_DH fails during an operation of integration. This flow of charge table target W_POSITION_DH.

    ODI-1228: SIL_PositionDimensionHierarchy.W_POSITION_DH (integration) of the task fails when connecting ORACLE target BIAPPS_DW.

    Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (DEV_DW. W_POSITION_DH_U2) violated

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:462)

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:405)

    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:931)

    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:481)

    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:205)

    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:548)

    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:217)

    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1115)

    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1488)

    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3769)

    at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3954)

    at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1539)

    at oracle.odi.runtime.agent.execution.sql.SQLCommand.execute(SQLCommand.java:163)

    at oracle.odi.runtime.agent.execution.sql.SQLExecutor.execute(SQLExecutor.java:102)

    at oracle.odi.runtime.agent.execution.sql.SQLExecutor.execute(SQLExecutor.java:1)

    at oracle.odi.runtime.agent.execution.TaskExecutionHandler.handleTask(TaskExecutionHandler.java:50)

    at com.sunopsis.dwg.dbobj.SnpSessTaskSql.processTask(SnpSessTaskSql.java:2913)

    at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java:2625)

    at com.sunopsis.dwg.dbobj.SnpSessStep.treatAttachedTasks(SnpSessStep.java:577)

    at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java:468)

    at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java:2093)

    at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java:1895)

    to oracle.odi.runtime.agent.processor.impl.StartScenRequestProcessor$ 2.doAction(StartScenRequestProcessor.java:580)

    at oracle.odi.core.persistence.dwgobject.DwgObjectTemplate.execute(DwgObjectTemplate.java:216)

    at oracle.odi.runtime.agent.processor.impl.StartScenRequestProcessor.doProcessStartScenTask(StartScenRequestProcessor.java:512)

    to oracle.odi.runtime.agent.processor.impl.StartScenRequestProcessor$ StartScenTask.doExecute (StartScenRequestProcessor.java:1068)

    at oracle.odi.runtime.agent.processor.task.AgentTask.execute(AgentTask.java:137)

    to oracle.odi.runtime.agent.support.DefaultAgentTaskExecutor$ 2.run(DefaultAgentTaskExecutor.java:82)

    at java.lang.Thread.run(Thread.java:662)

    How to solve the question above using ODI 11 g. I'm using Oracle ERP R12.1.3 as a source of data for this.

    Thanks in advance.

    Kind regards

    Saro

    What is the result of a query on table W_POSITION_DH or W_POSITION_D duplicate?

    Naeem

  • Get the "unique constraint" error while mapping custom jsp

    Hello

    We are implementing iStore R12 (12.1.3).

    We have customized ibeCCtdMenu.jsp, renamed as xxibeCCtdMenu.jsp and moved to $OA_HTML / folder.

    Now in the template Manager, we create a new source (xxibeCCtdMenu.jsp) file to the title of "model of generation of Menu".

    However when we select site and language like 'All', it gives following error:
    Error in the logical record of physical mapping
    ORA-00001: unique constraint (IBE. IBE_DSP_LGL_PHYS_MAP_U2) violated in the package IBE_PhysicalMap_GRP procedure save_physicalmap
    All the sites and all the language already exists exists for 7670 deliverable

    How can we overcome them this error? Please notify.
    Thank you
    Vivek

    for a given Site and the language combination, can exist only one model.
    Default file provided by Oracle is set with combination like all Sites - all languages, and you will not be able to change it.

    Save your file with combination such as all Sites - English
    or , all languages.

    Then it will work fine.

    Hrishikesh

  • Unique constraint shot while refreshing in the MERGE statement.

    Hi guys

    I have a question that I can't solve. Would appreciate any help on this. The configuration of the data and the script is as below.
    SQL*Plus: Release 10.2.0.1.0 - Production on Wed May 4 11:46:02 2011
    
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    
    
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    
    SQL> 
    
    create table table_1
    (id number,
     id_name varchar2(20));
     
    Alter table table_1 add primary key(id);
    
    create table table_2
    (id number,
     id_name varchar2(20));
     
     insert into table_2 values (1, 'id_1');
     insert into table_2 values (2, 'id_2');
     insert into table_2 values (1, 'id_1_upd');
    
    SQL> select * from table_1;
    
    no rows selected
    
    SQL> select * from table_2;
    
            ID ID_NAME
    ---------- --------------------
             1 id_1
             2 id_2
             1 id_1_upd
    
    SQL> 
    
    SQL>  merge into table_1 target
      2   using (select id, 
      3                 id_name
      4            from table_2) source
      5   on (source.id = target.id)
      6   when matched then
      7      update set target.id_name = source.id_name
      8   when not matched then
      9      insert(id,
     10             id_name)
     11      values(source.id,
     12             source.id_name);
     merge into table_1 target
    *
    ERROR at line 1:
    ORA-00001: unique constraint (SYS_C00137508) violated
    
    SQL> ed
    Wrote file afiedt.buf
    
      1  select constraint_type, table_name, status
      2*   from user_constraints where constraint_name = 'SYS_C00137508'
    SQL> /
    
    C TABLE_NAME                     STATUS
    - ------------------------------ --------
    P TABLE_1                        ENABLED
    Can someone help me please to solve this as the actual code that I am developing has the same configuration and I am constantly getting this error. As long as the same record does not come to the top in the 'source' table, MERGE performs an update or an insert.
    But as a "duplicate" coming soon to update, I get the error of unique constraint.

    Thank you
    -K.B.

    Dear Sir

    ERROR at line 1:
    ORA-00001: unique constraint (SYS_C00137508) violated
    

    You think two things

    (a) coherent reading: what was the situation of table_1 when the maching clause was initially assessed. There were 0 insert rows that correspond to which means that the merge operation will be all
    (b) your corresponding clause has a problem: the join column must be unique in both tables the case the merger will be ambiguous. You do not have a unique key on the source table
    (c) think that the merge operation will never insert id = 1 and then update id = 1 within the same operation. Will never happen

    Hope this helps

    Mohamed Houri

  • Index naming standards does not and unique constraints

    I found yet another question of naming standards

    I have tried to create a unique constraint as a normal index via the unique constraints and indexes in Properties of Table with the assumption that it will use the design properties of models.  This isn't.

    Naming Standard Template.jpg

    As noted in the image of the model above, my Unique constraint model is {table} _ {columns} lancement_remarques

    and my model of Index idx _ {columns} {table}.  Yet, when I try to create the Unique constraint, it creates the naming convention in names like CUSTOMER_ADDRESS__UK (2 lines of underscore?) as shown below.

    Table_Props_Unique_Constraint.jpg

    My assumption is that he needed a column, so I added the column and also applied the rules naming - nothing.

    Table_Props_Unique_Constraint_w_Column.jpg

    Is my wrong assumption on these constraints being appointed through the models?  If this is not the case, what naming rules is in this context?

    The same behavior is evident when you try to create index.

    I get not all comments on my posts.  Are these bugs or just user error?

    Hello

    Thank you to report the problem, I logged a bug. You can get 'Rules of naming' works properly if you press the button 'Apply' before that.

    I get not all comments on my posts.

    I don't think that anyone (or any job) has been ignored on this forum. Depending on the complexity of the problem and our current commitment (other urgent tasks, holidays, time zone), you can get answer almost immediately or after a certain time.

    It is useful for us, if you mark your messages as replied if you get the right answer.

    Philippe

  • Questions about NOVALIDATE ALLOW a constraint

    I have run the command on Oracle 11.2.0.1 on Redhat 5.2
    SQL> alter table agency add constraint agency_agcy_ori unique (agcy_ori) ENABLE NOVALIDATE;
    alter table agency add constraint agency_agcy_ori unique (agcy_ori) ENABLE NOVALIDATE
                                      *
    ERROR at line 1:
    ORA-02299: cannot validate (DEVPF.AGENCY_AGCY_ORI) - duplicate keys found
    I knew that the table has two copies and null in the column in which I want to add a unique constraint. Using NOVALIDATE, I expected tolarates exist it in double and valid new data added to the uniqueness. Because it says in Oracle DOc B28286 (page 8-15)
    ENABLE NOVALIDATE ensures that all new DML operations on the constrained
    data comply with the constraint. This clause does not ensure that existing data in
    the table complies with the constraint
    However, my database is inconsistent with that. I misunderstood the doc?

    Other related issues
    (1) I have two rows with the agcy_ori column is NULL. Who would consider duplicate and fails to VALIDATE when create a unique constraint.
    (2) the same doc shows also (page 8-16)
    DISABLE VALIDATE disables the constraint and drops the index on the constraint,
    but keeps the constraint valid. This feature is most useful in data warehousing
    situations, because it lets you load large amounts of data while also saving space
    by not having an index. This setting lets you load data from a nonpartitioned table
    into a partitioned table using the exchange_partition_clause of the ALTER
    TABLE statement or using SQL*Loader. All other modifications to the table
    (inserts, updates, and deletes) by other SQL statements are disallowed
    This raises more questions:
    (a) turn OFF VALIDATE a unique constraint drop the unique index but always validate uniqueness. That is to say than the uniqueness of remained you without a unique index. If it is possible, why ALLOW a unique constraint need create a unique index?
    (b) the last setense "all changes to the table by the other SQL statements are not allowed. This makes the table read only with the exception of partition/nonpartition and SQL * LOADER. This can be a useful feature, but I don't see the logic here: cannot update Column2 of the table just because a constraint in column 10 is DISABLE VALIDATE.

    Hope that people can help me here. Thank you.

    It won't work if you create a non-unique index for the constraint.

    SQL> create table test (nn number);
    Table created.
    SQL> create index te on test (nn) ;
    Index created.
    SQL> insert into test values (1);
    1 row created.
    SQL> insert into test values (1);
    1 row created.
    SQL> alter table test add constraint ttt unique (nn) using index te enable novalidate;
    Table altered.
    SQL> select * from test;
    
            NN
    ----------
             1
             1
    
    2 rows selected.
    
  • correct handling of foreign keys in unique constraints for operations ON DELETE SET NULL

    During my troubleshooting at a client site, I came across an interesting setup where I would like to ask your opinion.


    Consider two tables ADTB and TBLB.

    ADTB:

    INT COLA1

    COLA2 INT

    TBLB:

    COLB1 INT

    COLA2 is COLB1 as a foreign key ON DELETE SET NULL value.

    COLA1 and COLA2 are combined into a UNIQUE for the BATTERY constraint.

    I have two records of TBLB:

    (1)

    (2)

    and two DRUM recordings:

    (1, 1)

    (2, 2)

    so far, all the constraints are valid.

    During my research, I learned that I can not put COLA2 null in ADTB for two lines at the same time:

    TBLA UPDATE set COLA2 = NULL where COLA1 = 1;

    -> OK

    TBLA UPDATE set COLA2 = NULL where COLA1 = 2;

    -> VIOLATED UNIQUE CONSTRAINT

    Unfortunately, it's something my application needs, anyway. In order to get this resolved, but I try to understand, what would happen if I:

    REMOVE THE TBLB;

    ?

    It should set COLA2 in ADTB "Null" on the two lines, which is not allowed due to the UNIQUE CONSTRAINT.

    Can someone shed light on this issue? Thank you.


    Yours,

    Ronny

    Unfortunately, as you say, you can't not NULL values in such a unique constraint.  It would be the same as if you had a composite primary key and try to allow one of the columns will be null in several rows with the same value in the other column.  NULL is treated as an "unknown" value, it is possible that it could be the same value (it may or may not be, but Oracle does not know), so it must assume that it might be and that's why treat it as if there is the potential for a duplicate... so it's not unique.

    In short, do not allow null values in your unique constraints.

    The default is in the drawing, not in the way that Oracle is the treatment.  Fix the design if you do not have NULL values.

    In terms of relational database design, it seems that you are trying to transform the 1:M relations M:M relations, and which requires an intermediate table if you have M:1 and 1:M between 3 tables instead.

  • Unique constraint on the values in both directions

    I'm looking to create a unique constraint that works in two ways. Say I got a constraint unique in columns 1 and 2. I want it to be impossible for the two lines below the two exist at the same time. Is there a way to do this? I googled around for a while now and I found nothing that works so far.

    Header 1 Header 2
    DogCAT
    CATDog

    Hello

    You can create an index based on a single function:, like this:

    CREATE UNIQUE INDEX table_x_header_1_header_2

    ON table_x (LESS (header_1, header_2)

    More LARGE (header_1, header_2)

    );

    How will you use these values?  You might be better to simply create a regular old unique constraint, but also have a CHECK constraint to ensure that header_1<= header_2. ="" that="" way,="" when="" you="" want="" to="" search="" for="" the="" combination="" ('cat',="" 'dog')="" you="" won't="" have="" to="" search="" for="" ('dog',="" 'cat')="">

  • Oracle DB: Check Unique constraints before award of sequence (ID)

    Hello!

    I am building a Java web application using JPA.

    I used to fill the table IDs, sequences of generators, reported through DB and javax.persistence annotation (@Sequence).

    Some tables have simple unique constraints (example: Table_Country: Country column "country_name" must be Unique).

    At the time of execution, trying to persist a country name that is already in my Table_Country, java will throw exception: OK. But I noticed: before that, DB has allocated a sequence ID to my object.

    My question is: there's way (apart from making programmatic or triggers for and during the audit) of database to check unique constraints before award of sequence?

    Thanks in advance!

    My question is: there's way (apart from making programmatic or triggers for and during the audit) of database to check unique constraints before award of sequence?

    No - for several reasons.

    1. the real constraint is not verified by Oracle until you provide the values you are using Oracle.

    2. If you try to perform the audit before giving the value to Oracle another user could enter this value and insert it before you and which would still cause your problem.

    Oracle is a multi-user system. Even if you try to "look" at the next value in the sequence other users could easily allocate this value until you can get it so the value you 'read' would really not be the value you get.

    You can't tell what the value of the next sequence will be except by actually calling NEXTVAL to return.

    As others have said it seems that yours is a JPA number.

  • Indexes and UNIQUE constraints

    For a TEST table (col1, col2, col3,...), I put the UNIQUE constraint as follows:

    ALTER table TEST add constraint test_uniq UNIQUE col1, col2, col3);

    It is said that when the UNIQUE constraint is created, ORACLE also creates an index on (col1, col2, col3) automatically. But sometimes, I use only one of the columns in the WHERE clause as col1 = xxx, or col2 = yyy.

    Create separate indexes, one for col1 and col2? I think that even if the creation of the UNIQUE constraint also created an index. But this index is a composite index that is for the dosage of col1, col2 and col3 simultaneously (is that correct)? If so, create an index for col1 and col2 will be necessary?



    Thank you for helping.

    Scott

    If there is an index on (col1, col2, col3) and ask about col1, the index will be used.

    If you have questions about col2, it can (index skip scan) or maybe not.

    If you ask about col3 then it will not be used.

    So if you think that there will be queries with col3 in where clause and they can benefit from an index, you can create it.

  • Unique constraint violation error

    Hi all

    I have a procedure called - FHM_DASHBOARD_PROC which inserts data into a table called FHM_DASHBOARD_F retrieve records in multiple tables. However, for a particular type of record, these data are not inserted because of the Unique constraint violation

    the procedure is:
    create or replace
    PROCEDURE FHM_DASHBOARD_PROC AS
    
    DB_METRICS_CNT1Z number;
    --V_PODNAME varchar2(10);
    V_KI_CODE_DB_STATSZ varchar2(50);
    V_ERRORSTRING varchar2(100);
    
    --CURSOR PODNAME_CUR IS SELECT PODNAME,SHORTNAME FROM CRMODDEV.POD_DATA WHERE PODSTATUS_ID=1 AND PODTYPE_ID=1 ORDER BY PODNAME;
    
    
    -- DB STATS
    
    BEGIN 
    
      -- OPEN PODNAME_CUR;
        --   LOOP
          --   FETCH PODNAME_CUR INTO V_PODNAME,V_POD_SHORTNAME ;
            -- EXIT WHEN PODNAME_CUR%NOTFOUND;
    
               BEGIN
               
                     SELECT COUNT(*) INTO DB_METRICS_CNT1Z FROM FHM_DB_METRICS_F A, FHM_DB_D B where A.DBNAME=B.DBNAME and PODNAME=V_PODNAME AND DB_DATE=TRUNC(SYSDATE-1);
                               DBMS_OUTPUT.PUT_LINE('DB_METRICS_CNT1Z :'|| DB_METRICS_CNT1Z);
                               IF DB_METRICS_CNT1Z >0 THEN
                             
                        DBMS_OUTPUT.PUT_LINE('DB STATS');
                                  
                       INSERT INTO FHM_DASHBOARD_F(PODNAME,DASH_DATE,KI_CODE,KI_VALUE,KI_STATUS)
                                  
                          (SELECT PODNAME, DASH_DATE AS CU_DATE, KI.KI_CODE, NVL(PF.KI_VALUE,0), 
                                                                  CASE
                                                                   WHEN PF.KI_VALUE = ki.warning_threshold then 2
                        when PF.KI_VALUE=0 then 0
                        ELSE 1 
                        END  AS ALERT_STATUS
                        
                        FROM 
                        
                        (SELECT PODNAME,DB_DATE AS DASH_DATE,decode(a.stats_last_status,'SUCCEEDED',1,'FAILED',2,'STOPPED',2,NULL,0) KI_VALUE from  
                        FHM_DB_METRICS_F a,fhm_db_d b where a.dbname=b.dbname and podname='XYZ' and db_date=TRUNC(SYSDATE-1) and dbtype='OLTP')PF,
                        FHM_KEY_INDICATOR_D KI where PF.PODNAME=KI.POD_NAME AND KI.TIER_CODE=3 AND KI.KI_NAME='DB_STATS'
                        AND (PF.PODNAME,TRUNC(PF.DASH_DATE),KI.KI_CODE) NOT IN (SELECT PODNAME,DASH_DATE,KI_CODE FROM FHM_DASHBOARD_F)); 
                                 COMMIT;
                     
                             ELSE
                                    SELECT KI_CODE INTO V_KI_CODE_DB_STATSZ FROM FHM_KEY_INDICATOR_D WHERE POD_NAME=V_PODNAME AND KI_NAME='DB_STATS';
                                     DBMS_OUTPUT.PUT_LINE('V_KI_CODE_DB_STATSZ :'||V_KI_CODE_DB_STATSZ);
                                     INSERT INTO FHM_DASHBOARD_F(PODNAME,DASH_DATE,KI_CODE,KI_VALUE,KI_STATUS) VALUES(V_PODNAME,TRUNC(SYSDATE-1),V_KI_CODE_DB_STATSZ,0,0); 
                                     COMMIT; 
                                     
                             END IF;
                            
         EXCEPTION
                            WHEN OTHERS THEN
                            V_ERRORSTRING :='INSERT INTO FHM_DASHBOARD_F_ERROR_LOG(POD_NAME,KI_NAME,ERRORNO,ERRORMESSAGE,DATETIME) VALUES
                   ('''||V_PODNAME||''',''DB_STATS'','''||SQLCODE||''','''||SQLERRM||''',SYSDATE)';                         
                   EXECUTE IMMEDIATE  V_ERRORSTRING;
                            COMMIT;
              END;
    
          --END LOOP;
      --CLOSE PODNAME_CUR;
    
    
    END;
    
    
    END FHM_DASHBOARD_PROC;
    and the table where data integration is
    CREATE TABLE "CRMODDEV"."FHM_DASHBOARD_F"
      (
        "PODNAME" VARCHAR2(25 BYTE) NOT NULL ENABLE,
        "DASH_DATE" DATE,
        "KI_CODE"   NUMBER NOT NULL ENABLE,
        "KI_VALUE"  NUMBER,
        "KI_STATUS" NUMBER,
        CONSTRAINT "FHM_DASHBOARD_F_DATE_PK" PRIMARY KEY ("DASH_DATE", "PODNAME", "KI_CODE") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 NOLOGGING COMPUTE STATISTICS STORAGE(INITIAL 4194304 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "CRMODDEV_IDX" ENABLE,
        CONSTRAINT "FHM_DASHBOARD_F_KI_CODE_FK" FOREIGN KEY ("KI_CODE") REFERENCES "CRMODDEV"."FHM_KEY_INDICATOR_D" ("KI_CODE") ENABLE
      )
      PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS NOLOGGING STORAGE
      (
        INITIAL 3145728 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT
      )
      TABLESPACE "CRMODDEV_TBL" ENABLE ROW MOVEMENT ;
    the constraint primary key is FHM_DASHBOARD_F_DATE_PK and is on 3 columns of the table, DASH_DATE, PODNAME, KI_CODE



    And it's the query used in the procedure to insert the data into the table
    (SELECT  PODNAME, DASH_DATE AS CU_DATE, KI.KI_CODE, NVL(PF.KI_VALUE,0), 
                                   CASE
                                   WHEN PF.KI_VALUE = ki.warning_threshold then 2
    when PF.KI_VALUE=0 then 0
    ELSE 1 
    END  AS ALERT_STATUS
    From 
    (Select  Podname,Db_Date As Dash_Date,Decode(A.Stats_Last_Status,'SUCCEEDED',1,'FAILED',2,'STOPPED',2,Null,0) Ki_Value From  -- Added Distinct
    FHM_DB_METRICS_F a,fhm_db_d b where a.dbname=b.dbname and podname in ('XYZ') and db_date = TRUNC(SYSDATE-2) and dbtype='OLTP')PF,
    Fhm_Key_Indicator_D Ki Where Pf.Podname=Ki.Pod_Name And Ki.Tier_Code=3 And Ki.Ki_Name='DB_STATS'
    And (Pf.Podname,Trunc(Pf.Dash_Date),Ki.Ki_Code) Not In (Select Podname,Dash_Date,Ki_Code From Fhm_Dashboard_F));
    It gives * record * 2 suite
    ---------------------------------------
    XYZ JANUARY 20 12 2521 1 1
    XYZ JANUARY 20 12 2521 1 1

    It gives the Unique constraint violation error when inserting. Then, I changed in the above insertion code by adding a distinct clause. Once the query gives only a SINGLE record accordingly. However, this record is not be inserted into the table and give the same error.

    Now the question is how should I insert that record into the table with success?


    If the message is too long, however, I gave you the real structure of the object or procedure and error.

    Thank you in advance.

    When you have 5 columns in the game adding THAT SEPARATE is n ot solution that you can still get the same error once.

    Check the target table if the data exists before inserting... If this is not the case, check the structure of the table for a unique constraint created on other columns.

    select *from 
    where
    DASH_DATE=date '2012-01-20'
    and PODNAME='XYZ'
    and  KI_CODE=2521;
    
  • composite unique constraint on the values of parent and child?

    Is it possible to have a composite unique constraint that contains the values of the child elements? The example below has the "child" elements are offline, but it's preferred, but optional, I know that you can have a unique constraint in the set of tables without using a reference table that contains the constraint and the two columns. How xdb manages this requirement?

    permit:
    <parent ID="1">
       <child><name>test1</name></child>
       <child><name>test2</name></child>
    </parent>
    <parent ID="2">
       <child><name>test1</name></child>
       <child><name>test2</name></child>
    </parent>
    not allowed:
    <parent ID="1">
       <child><name>test1</name></child>
       <child><name>test1</name></child>
    </parent>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
               xmlns:xdb="http://xmlns.oracle.com/xdb"
               xdb:storeVarrayAsTable="true"
               elementFormDefault="qualified">
        
        <xs:element name="parent" type="Parent_T"
            xdb:columnProps="CONSTRAINT parent_pkey PRIMARY KEY (XMLDATA.ID)"
            xdb:defaultTable="PARENT"/>
    
        <xs:complexType name="Parent_T" xdb:SQLType="PARENT_T" xdb:maintainDOM="false">
            <xs:sequence>
                <xs:element name="child" type="Child_T" minOccurs="1" maxOccurs="unbounded" xdb:SQLName="CHILD"
                          xdb:SQLInline="false" xdb:defaultTable="CHILD" "/>
            </xs:sequence>
            <xs:attribute name="ID" xdb:SQLName="ID" use="required" />
        </xs:complexType>
        
        <xs:complexType name="Child_T" xdb:SQLType="CHILD_T">
           <xs:sequence>
             <xs:element name="name" type="xs:string" xdb:SQLName="NAME"/>
           </xs:sequence>
         </xs:complexType>     
    </xs:schema>
    xdb:columnProps = "CONSTRAINT parent_pkey PRIMARY KEY (XMLDATA.ID), * UNIQUE (XMLDATA.» "Child.Name) *" triggers the non-existent attribute


    A possible solution would be to copy the value of the primary key parent of the child element, then I could create a composite unique constraint using only the values of the child. However, I have this same requirement elsewhere in my lowest nested schema, and it can become messy / bad design with cascading of all primary keys on the schema. For example, I have a recursive element in which two attributes must be unique only within the parent company:
    <parent id="1">
       <child a="1" b="1">
          <child a="1" b="2">
             <child a="1" b="1" /> *not allowed
          </child>
       </child>
       <child a="1" b="2" /> *not allowed
    </parent>
    Possible solution:
    <child a="1" b="2" parent_id="1" />
    <xs:complexType name="Child_T>
       <xs:sequence>
          <xs:element name="child" xsd:SQLInline="false" xsd:columnProps="UNIQUE(XMLDATA.a,XMLDATA.b,XMLDATA.parent_id)" minOccurs="0" maxOccurs="unbounded" type="Child_T">
       </xs:sequence>
       </xs:element
    </xs:complexType>
    Is there a better design?

    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi 
    PL/SQL Release 10.2.0.4.0 - Production                           
    CORE     10.2.0.4.0     Production                                       
    TNS for Linux: Version 10.2.0.4.0 - Production                   
    NLSRTL Version 10.2.0.4.0 - Production 

    You can do something like this:

    SQL> DECLARE
      2
      3    xsd_doc xmltype := xmltype('
      4  
      5    
      6      
      7        
      8          
      9        
     10      
     11    
     12    
     13      
     14        
     15          
     16        
     17      
     18    
     19    
     20      
     21        
     22          
     23        
     24        
     25      
     26    
     27    
     28      
     29        
     30          
     31        
     32      
     33    
     34  ');
     35
     36  BEGIN
     37
     38    dbms_xmlschema.registerSchema(
     39      schemaURL => 'test_parent.xsd',
     40      schemaDoc => xsd_doc,
     41      local => true,
     42      genTypes => true,
     43      genbean => false,
     44      genTables => false,
     45      enableHierarchy => dbms_xmlschema.ENABLE_HIERARCHY_NONE
     46    );
     47
     48  END;
     49  /
    
    PL/SQL procedure successfully completed
    
    SQL> CREATE TABLE my_xml_table OF XMLTYPE
      2  XMLTYPE STORE AS OBJECT RELATIONAL
      3  XMLSCHEMA "test_parent.xsd"
      4  ELEMENT "root"
      5  VARRAY xmldata."parent" STORE AS TABLE my_parent_tab
      6  (
      7    VARRAY "child" STORE AS TABLE my_child_tab
      8  )
      9  ;
    
    Table created
    
    SQL> ALTER TABLE my_parent_tab ADD CONSTRAINT parent_uk UNIQUE (nested_table_id, "ID");
    
    Table altered
    
    SQL> ALTER TABLE my_child_tab ADD CONSTRAINT child_uk UNIQUE (nested_table_id, "name");
    
    Table altered
     
    

    Then:

    SQL> insert into my_xml_table values (
      2  xmltype('
      3     test1
      4     test2
      5  
      6  
      7     test1
      8     test2
      9  ')
     10  );
    insert into my_xml_table values (
    *
    ERREUR à la ligne 1 :
    ORA-00001: violation de contrainte unique (DEV.PARENT_UK)
    
    SQL> insert into my_xml_table values (
      2  xmltype('
      3     test1
      4     test1
      5  
      6  
      7     test1
      8     test2
      9  ')
     10  );
    insert into my_xml_table values (
    *
    ERREUR à la ligne 1 :
    ORA-00001: violation de contrainte unique (DEV.CHILD_UK)
    
    SQL> insert into my_xml_table values (
      2  xmltype('
      3     test1
      4     test2
      5  
      6  
      7     test1
      8     test2
      9  ')
     10  );
    
    1 ligne créée.
    

    http://download.Oracle.com/docs/CD/B19306_01/AppDev.102/b14259/xdb06stt.htm#sthref987

  • Unique constraint during the race error collecting statistics of schema

    Hello
    I get this error periodically during execution to collect statistics of schema
    In GATHER_SCHEMA_STATS , schema_name= ALL percent= 40 degree = 8 internal_flag= NOBACKUP
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    Unable to correctly update the history table - fnd_stats_hist.
    -1 - ORA-00001: unique constraint (APPLSYS.FND_STATS_HIST_U1) violated
    I went thru notes 470556.1 , but I have not applied patch 5876047 according to the note.

    I can truncate table FND_STATS_HIST? Is it safe to truncate this table?

    Thank you
    ARS

    Published by: user7640966 on January 2, 2011 23:58

    Hi Ars;

    If I suggest his prod, make sure you have a valid backup of your system and also raise sr and confirm with oracle support. If you are on the clone or test, such as mention of doc first to backup table FND_STATS_HIST (make sure that you have a valid backup), truncate and repeat the test question

    Respect of
    HELIOS

  • Unique constraint violation

    I just got an error of constraint unique violation when I tried to insert a row in a table.
    But even after that I deleted the PK constraint on the table in question, I still get the same error message when I try again the insert:
    SQL error: ORA-00001: unique constraint (GILLNET_TAG. DELETED_AUTH_PK) violated
    00001 00000 - "forced single (s.%s) violated."
    * Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
    For Trusted Oracle configured in DBMS MAC mode, you can see
    This message if there is an entry double at a different level.
    * Action: Either remove the single restriction or not to insert the key.

    Can someone tell me why? The removal of the constraint simply not registered with SQL Developer?
    Thank you.

    Because you have only removed the constraint, not the corresponding unique index.

    But... Why are you doing it? The unique constraint is there for a reason.

  • Unique constraint with conditions?

    Hi all!

    I have the following scenario... I need column UNIQUE Serial_number forced but only when the STATUS column = 'Y '. Serial_number can be non-unique, where the STATE has another value or is set to null. So, I couldn't en with this:

    SERIAL_NUMBER | STATUS
    --------------------------------------
    123456789 N
    123456789 N
    123456789 IS

    but a new line with 123456789 and 'Y' should not be allowed.

    Is this possible with a UNIQUE constraint, or what I have to set in a trigger? I was playing with the UNIQUE constraint for a while, but neither DECODE, WHERE clauses seem to be accepted...

    Thanks in advance!

    Try this:

    create unique index a1 on tab(case when STATUS = 'Y' then SERIAL_NUMBER else null end);
    

    Amiel

Maybe you are looking for