Database constraint check.

Hi I want to add a db check constraint that acts like a unique but its on two columns not one & only i one of the columns is NOT NULL. So if column one is null then i do not want a check but if column one is NOT NULL then check that column one, column two are a unique combination
for example
column 1 column 2
1 1
1 2
1 3
2 1
2 2
null 2
all above are ok.
2 2
this should error as not unique.
Any help much appreciated

Dear,
mhouri> create table t_uk
  2      as
  3      select 1 c1, 1 c2 from dual union all
  4      select 1 c1, 2 c2 from dual union all
  5      select 1 c1, 3 c2 from dual union all
  6      select 2 c1, 1 c2 from dual union all
  7      select 2 c1, 2 c2 from dual;
Table created.
mhouri> alter table t_uk add constraint uk unique (c1, c2);
Table altered.
mhouri> create unique index t_uk_ind on t_uk
  2  (case when c1 is null then 1 else c1 end,
  3   case when c2 is null then 1 else c2 end)   ;
Index created.
mhouri> insert into t_uk values (null,2);
insert into t_uk values (null,2)
ERROR at line 1:
ORA-00001: unique constraint (xxx.T_UK_IND) violated
mhouri> insert into t_uk values (2,null);
insert into t_uk values (2,null)
ERROR at line 1:
ORA-00001: unique constraint (xxx.T_UK_IND) violated
mhouri> insert into t_uk values (2,2);
insert into t_uk values (2,2)
ERROR at line 1:
ORA-00001: unique constraint (xxx.UK) violated
mhouri> insert into t_uk values (2,3);
1 row created.Hope this helps and is correct
Best regards
Mohamed Houri

Similar Messages

  • How can I use database constraints in entity attribute validation rules

    I am interested in using database constraints to validate attributes in entity objects.
    I would like to implement a JboValidatorInterface in a way that I can use an operator like "GreaterOrEqualTo" to compare with values retrieved from the database for a column associated with an entity object attribute.
    I have used this pattern with success in other environments, where the user community decides the minimum value for a thing should change from x to y, and simply changing a database object also changes the validation methods of all applications which access it.
    I am not certain that column constraints are the appropriate vehicle, but so far that seems to be the case.
    I see that you can create a validation rule which makes comparisons against a view object attribute. I am wondering if there is a generic way to use standardized names for column constraints along with ADF hooks into properties of database columns, to avoid writing individual queries for each attribute.
    Thanks in advance!!!

    Jeffrey,
    If you already have constraints on the underlying tables, why do you need to validate them in ADF BC? You can certainly use some framework extension classes to give the user nicely formatted error messages - see ER: ADF BC - allow custom error msgs for common exceptions (e.g. DML) for more details.
    I am using this method so that anything that is enforced in the database (check constraints, foreign keys, unique constraints, etc) are not enforced in the ADF BC layer as well - after all, there's more than one way to get data into a table, and DB constraints ensure that even if data gets in through another mechanism (apart from the ADF application), it is valid. My 2 cents, of course.
    Hope this helps,
    John

  • Constraint Checking Vs After Row Trigger

    According to db concepts Chap 17 Trigger -> Trigger Execution, integrity checking is performed BEFORE the after row trigger executed. I guess this is not 100% true. AFAIK, we can create an AFTER ROW trigger on a child table which automatically insert new referenced row in the parent table. e.g.
    CREATE TABLE child (
    child_id int primary key,
    parent_id int references parent,
    CREATE TABLE parent (
    parent_id int primary key,
    CREATE OR REPLACE TRIGGER A
    AFTER INSERT OR UPDATE on child
    FOR EACH ROW
    BEGIN
    INSERT INTO parent values (:new.parent_id,...);
    END;
    If the constraint checking is done before the trigger, the referential integrity should have been violated when the child row is inserted.
    So if the documentation is wrong, when will the constraint checking be carried out with respect to trigger execution.

    There are plenty of things that are easier and/or safer to do in an AFTER ROW trigger, since can see exactly what the data in the row has been set to by any BEFORE ROW triggers and you can't change the data inadvertently. If your BEFORE ROW triggers are calling relatively complex procedures owned by various disparate groups of developers, it can be non-trivial to ensure that every groups changes are perfectly coordinated. AFTER ROW triggers are a heck of a lot easier to deal with here because you don't have to worry about another section of code changing the data you're using to make your decision.
    I'm hard pressed to think of something that couldn't possibly be accomplished in a BEfORE ROW trigger, though I suspect there are at least a few oddball situations.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Database constraint

    Hi,
    The rule of thumb state that not to implement business logic in database trigger and stored procedure.
    How about database constraint? Is that means we can eliminate the database constraint, and then develop all the validation logic in EJB or java bean?
    Which approach is correct? DB constraint or EJB?
    Pls give some suggestion and advise.

    Consider the SQL script below, which return in Oracle:
    CREATE TABLE s_customer
    (customer_id NUMBER(7) CONSTRAINT s_customer_id_nn NOT NULL,
    name VARCHAR2(50),
    local VARCHAR2(1) DEFAULT 'Y' NOT NULL,
    CONSTRAINT const_local CHECK (local IN ('Y', 'N')),
    CONSTRAINT customer_id_pk PRIMARY KEY (customer_id)
    See that the 'local' column of s_customer table does have a validation check for either Y or N.
    customer_id have constraint of primary key.
    Ok, let say design decision to use EJB, so can i put the 'local' column validation in EJB or java bean. But the primary key constraint maintain in database.
    Is is GOOD to design in this way?

  • Database constraints propagated to entity

    I'm trying to determine which database constraints are propagated to an entity when the entity is generated from a table.
    From what I can tell, it looks like
    <ul><li>primary key</li>
    <li>not null</li>
    <li>unique key</li>
    <li>precision</li>
    <li>foreign key (via
         associations)</li>
    </ul>
    are honored in the entity.
    <ul><li>check constraints</li>
    <li>default values</li>
    </ul>
    are not carried over.
    However, even though some constraints are carried over, does this mean they are enforced (or validated)?
    It looks like the following Validation rules are created:
    <ul><li>Not Null constraints --&gt; Database Constraint - Mandatory</li>
    <li>Precision constraints --&gt; Database Constraint - Precision</li>
    </ul>
    Do the rest--even the Primary Key constraint-need to be created as Validation rules in the entity? The documentation is not very clear on this.
    Thanks.

    Please read under Unique Key Validator
    http://one-size-doesnt-fit-all.blogspot.com/2007/08/jdev-11g-new-features-adf-bc-entity.html
    Unique Key Validator - has changed somewhat and now allows you to define validation on primary and unique keys defined for the EO (indirectly derived from the underlying table). In addition you may define multiple Unique Key Validators against the one EO where the 10.1.3 release limited this to one.
    In summary the 10.1.3 release introduced the basic declarative validators against Entity Objects in ADF Business Components. Within the 11g release this has given the JDeveloper team the opportunity to go beyond the obvious validation requirements and give sophisticated declarative business rule validation still with the advantage of minimal to no coding required.

  • Deferrable database constraint

    I am using JDev 9.0.5.2, ADF, UIX, and struts.
    I have a deferrable database constraint so that it is checked during commit. My question is where can I catch this to give a user friendly error message. I usually catch constraint messages in the doDML method in the entity objects Impl class. I tried the beforeCommit and afterCommit methods but they didn't work either.
    Thanks for any help.

    you can caught exceptions in findForward method:
    ArrayList excList=ctx,getBindingContainer().getExceptionList();
    all items are oracle.jbo.JboException.
    you iterate exceptions; native exception are those exceptions where
    hasExceptions() return false.
    catched your exception, you can alter standard forward: ctx.setAcionForward(errorForward);
    i hope i helped you!
    I am using JDev 9.0.5.2, ADF, UIX, and struts.
    I have a deferrable database constraint so that it is
    checked during commit. My question is where can I
    catch this to give a user friendly error message. I
    usually catch constraint messages in the doDML method
    in the entity objects Impl class. I tried the
    beforeCommit and afterCommit methods but they didn't
    work either.
    Thanks for any help.

  • EJB3 + Database constraint

    Hi,
    Whats the prefered option to add Database constraints?
    @Table(uniqueConstraints = { @UniqueConstraint(columnNames = "a","b") } )
    would add a simple column based unique key.
    But how to add something more complex like a CHECK constraint?
    "CONSTRAINT ck_name length(a)>=5))"
    (Is there a possibility to plug some alter statements into the ddl generation process?)
    thx,
    Bernhard

    Consider the SQL script below, which return in Oracle:
    CREATE TABLE s_customer
    (customer_id NUMBER(7) CONSTRAINT s_customer_id_nn NOT NULL,
    name VARCHAR2(50),
    local VARCHAR2(1) DEFAULT 'Y' NOT NULL,
    CONSTRAINT const_local CHECK (local IN ('Y', 'N')),
    CONSTRAINT customer_id_pk PRIMARY KEY (customer_id)
    See that the 'local' column of s_customer table does have a validation check for either Y or N.
    customer_id have constraint of primary key.
    Ok, let say design decision to use EJB, so can i put the 'local' column validation in EJB or java bean. But the primary key constraint maintain in database.
    Is is GOOD to design in this way?

  • Custom Error Messages for Database Constraint Violations Problem

    Hi
    I have added a custom message bundle for the model project as explained in
    37.8.3 in the Fusion Developer's Guide - How to customize error messages for database constraint violations.
    http://download.oracle.com/docs/cd/E14571_01/web.1111/b31974/bcadvgen.htm#BABEFGCI
    Constraint Name : SYS_C0018574
    And I have following CustomErrorMessages class
    public class DBCustomErrorMessages extends ListResourceBundle {
        private static final Object[][] sMessageStrings =
            new String[][] { { "SYS_C0018574",
                               "Existing Record Found" } };
        protected Object[][] getContents() {
            return sMessageStrings;
    }This works fine when I run application model and adding records to vialate the constraint. So it gives me following message
    (oracle.jbo.DMLConstraintException) Existing Record FoundBut when run ui project it does not fire.
    Still it gives the message
    ORA-00001: unique constraint (CCBS2.SYS_C0018574) violatedCould you please shed some light?
    Edited by: deshan on Mar 15, 2011 11:28 AM

    Please see the image.
    http://4.bp.blogspot.com/-Fna66p-W5Jw/TX7uSQqqBtI/AAAAAAAAAH0/D1APg6oAIxI/s1600/1.JPG
    Error in Application Module ORA-00001: unique constraint (CCBS2.SYS_C0018574) violated exception is different from ui project.
    Any hint?
    Thanks
    deshan
    Edited by: deshan on Mar 15, 2011 10:16 AM

  • Error: SNAP_ADT does not exist in the database - manual check required

    Hello Friends,
    We are  performing an upgrade+migration to HDB using the DMO option(Oracle to HANA).
    We are getting below error in the phase MAIN_SHDCRE/SUBMOD_SHDDBCLONE/DBCLONE!
    Also find the output of SE11 & SE14 attached.
    SE14->
    Please help us with the manual check.
    Regards
    Sury

    Hi Sury,
    In regards to the error below:
    1EETGCLN Error: SNAP_ADT does not exist in the database -> manual check
    required
    1EETGCLN SNAP_ADT
    1EETGCLN Table does not exist
    Could you please try to activate the following tables via SE11?
    -  SNAP_ADT
    Once they are activated, Could you please repeat the phase and update the result?
    Thanks and Regards,
    James Wong
    Follow us:
    SAP System Upgrade & Update Troubleshooting Wiki Space.
    SAP Product Support Twitter  ( Hashtag: #NWUPGRADE)

  • JhsError Messages for Database constraint

    Hello JhaedStart Team
    I want to display mycustome entity alias name in place of entity name in Jhs Error messages for Database constraint , as you know we can customize this error message by replacing ConstraintName as a key in our registered customMessage Bundle (according to 25.8.3 sction of ADFdevelopers guide) .
    In order to do that I should disable JHS NLS generation for JHS because it's custome messages prevent my message to be display from my customMessage Bundle , So I have tried to delete constraint key (eg CASCADING_DELETE_VIOLATION) from GeneratorText.properties but I see that the CASCADING_DELETE_VIOLATION message still generated in my project JHS message bundle.
    Please help me to fix the problem

    JHeadstart also supports customizing database constraint messages, as explained in section 11.4 of the JHeadstart 10.1.3.2 Developer's Guide. So you don't need to use the technique of section 25.8.3 of the ADF Developer's Guide, you can customize the message directly in the JHeadstart resource bundle.
    Hope this helps,
    Sandra Muller
    JHeadstart Team
    Oracle Consulting

  • Database Health Check Enquiry

    Hi all,
    Some enquires regarding database health check. I did some research regarding health check, got overwhelmed by the information available out there.
    Currently I don't have any report on hand, but currently working and starting on one. This report serves as a report for reference, to understand if there's any database performance issue, and as a report for management.
    Wish to check with you folks, what are the typical things that I can look at on a daily basis to understand my database health status, eg. Buffer Hitrate, database I/O etc, especially those that may/will contribute to impact on the database performance. Or is there any good reference link whereby I can do some readup regarding such a health check?
    Thanks in advance for any input.
    Eugene

    Hi Eugene,
    Well that's a pretty open question and I guess you will get a lot of replies which I look forward to monitoring as there should be some very interesting ones there.
    Anyway, let me just open with one point that I have found very useful in the past. As regards Database Performance , you can look as much as you like at the statistics and a great deal of discretion is required in interpreting them but the real test for me of how well a database is performing is in terms of the user (or application) perception. Are the responses from the database good enough to meet the users expectations. Check the average response time for example and set guidellines for what is acceptable, very good response , very bad response etc.
    I use this as a guideline so then once the database is perfoming in the sense that the user is satisfied (or better still happy with the performance) we can gather the statistics (from Oracle 10g onwards there are lots of tools built in like ADDM and AWR for gathering and storing the database statistics) and create baselines. Once we have baselines for a normally performing system, as soon as problems are reported we can run off a diagnostic tool like ADDM for that period , compare it against the baseline and look for the striking differences. From there we can start an analysis of individual numbers, buffer hit ratios etc. to delve further.
    Hope this helps , I am sure lots of other people will chip in to this
    Regards

  • ITunes database integrity check?

    In iTunes I have a few ! that have appeared in the first column indicating iTunes can't find the file. So far I have found three folders (albums) that are missing from my music library disc and I don't understand how or when they dissappeared. I haven't found any individual missing files yet, just missing whole folders. It appears iTunes doesn't update the ! indicator until it has some reason to actually go open the file. Is there a way to automate this? So far I've been looking at each song with Command-I to check the Where info under Summary, or selecting the first song of an album and using Command-R to view the songs in finder. This is going to take a long time with nearly 8000 songs in my library. I'm trying to get an handle on the extent of the problem. I am careful to only use iTunes to manage the library (I don't move files around with finder). My library is on an external Firewire drive. Ideally, I would like there to be an "iTunes database integrity check" command.

    The MSDN documentation says "RESTORE VERIFYONLY" command does not verify whether the structure of the data contained within the backup set is correct. Does it mean the restore command will not able to detect corruption in the database and I just need to
    restore each of the backs starting from the latest to see if integrity check fails after restore ? OR RESTORE VERIFYONLY will confirm if the database is un-corrupted ?
    As the documentation suggests, RESTORE VERIFYONLY checks the structure of the backup but not the database itself.  You'll need to restore the backup to check the database consistency.
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

  • Database structure check

    Hello All,
    In the Live Cache alert monitor for a production system I am getting a red alert for the node "Database Structure Check" The message is "No data consistency check in the last three months"
    Can anyone please let me know if I can schedule the "Check database structure" from the DB Planning Calendar ( LC10 ) in the production system? Does it have any effect on the system performance?  If there is any prerequisite steps that need to done before running the "Check database structure" please let me know.
    The Live Cache version that is currently running is 7.6.02   BUILD 014-123-152-175.
    Thanks and Best Regards,
    Sanjay

    Hello Sanjay,
    you can use the TA DB13 or DB13C for planning the Check Data. But there are also other possibilities to do it. I think all you questions in the FAQ note to the Check Data procedure.
    Please try this link
    https://websmp230.sap-ag.de/sap(bD1kZSZjPTAwMQ==)/bc/bsp/spn/sapnotes/index2.htm?numm=940420&nlang=&smpsrv=
    If it doesn't work you can check the note 940420 directly.
    Best regards,
    Oksana Alekseious

  • Deferring Constraint Checking

    In the Oracle Lite documentation, there is a section:
    ==========================================================
    3.11.3.2 Defer Constraint Checking Until After All Transactions Are Applied
    1. Drop all foreign key constraints and then recreate them as DEFERRABLE constraints.
    2. Bind user-defined PL/SQL procedures to publications that contain tables with referential integrity constraints.
    3. The PL/SQL procedure should set constraints to DEFERRED in the BeforeApply function and IMMEDIATE in the AfterApply function as in the following example featuring a table named SAMPLE3 and a constraint named address.14_fk:
    ==========================================================
    For step 1, I am assuming this is on the base table that the publication references, since it is the one throwing the FK constraint violations at me.
    For step 2 however, are these procedures to be bound to the base tables as well, or somewhere else related to where the publication items are stored?
    Thanks,
    Allen

    In this case, the data model that I have to work with causes this situation
    TABLE A has 2 FK constraints to TABLE B
    TABLE B has 1 FK constraint to TABLE A
    In Oracle Lite, I:
    1-create a record in TABLE A where both of the columns with FK constraints are null
    2-create a record in TABLE B which refers to the original in TABLE A
    3-create a second record in TABLE B which also refers to the record in TABLE A
    4-update the record in TABLE A to refer to the 2 records in TABLE B
    When these changes reach the mobile server, they are placed in the error queue, because steps 1 and 4 are being combined and performed as one single insert. Since the records from step 2 and 3 don't exist yet, there is an FK violation.
    Is there a way to prevent the synchronization process from 'opitimizing' the transaction and combining steps 1 and 4? Everything works fine if I follow steps 1-4, but when 1 and 4 are combined it all falls apart.
    Thanks,
    Allen

  • Oracle 10g Database Health Check!

    Can anyone guide me the best way to perform a complete database health check?
    Thanks

    Metalink note:
    How to Perform a Healthcheck on the Database - 122669.1

Maybe you are looking for

  • Error while requesting for Service Request iview in ERP Common Role.

    Hi, I had assigned ERP Common role to a HR user and am trying to access pdf form from Service Request iview( I had done the configuration of Adobe in my portal).But i'am getting this error "The initial exception that caused the request to fail, was:

  • Misleading play count on movies

    This is probably more an idea than a problem, but I post it here to see what others think of it. We and our children love to watch movies on two iPads and on AppleTV. We are all sharing the same Home Sharing account. Many of the movies are played aga

  • Moving database 9i 32-bit to to be 10g on new hardware 64-bit

    Dear Gentlemen, I want to move a database 9.2.0.4.0 on windows server 2003 32-bit (Size=16GB) to be database 10G R2 on a new hardware with a windows server 2003 64-bit. can you explain the steps which i have to do to perform this issue?

  • WebForm isn´t availble!

    Hi Guys!                    I´m with problems to access the WebForm at my BPM 12c environment.                    When I go to my frevvo deployment test link, i get the response : "Permission denied"                   My log when i try to start a new

  • How can we implement SSO in SP2013

    Hi, How can we implement SSO from other applications to SP2013 web app. Please suggest with an example. Thanks, Krishna Krishnasandeep