0

I have a table and I am adding a constraint so if PaymentType is different than 'Check' to ensure that the CheckNumber is null. This is my table:

create table RegistrationHeader(
    RegistrationNo numeric 
    ,BillingID varchar(30) unique not null
    ,RegistrationDate date not null
    ,PaymentType varchar(5) check (PaymentType = 'CC' or PaymentType = 'PO' or PaymentType = 'Check') not null
    ,CCNumber varchar(16) check(LEN(CCNumber) = 16 OR LEN(CCNumber) = 15)
    ,PONumber varchar(30)
    ,CheckNumber varchar(10) default null
    ,primary key(RegistrationNo)
    ,constraint CC_CCNumber_constr check(
        (PaymentType = 'CC' and CCNumber is not null)
        or
        (PaymentType != 'CC' and CCNumber is null)
    )
    ,constraint PO_PONumber_constr check(
        (PaymentType = 'PO' and (PONumber is not null or PONumber != ''))
        or
        (PaymentType != 'PO' and PONumber is null)
    )
);

So, I have tried

,constraint CheckNumber_type_constr check((PaymentType = 'CC' or PaymentType = 'PO') and CheckNumber is null)

and

,constraint CheckNumber_type_constr check((PaymentType != 'Check') and CheckNumber is null)

and both fail miserably...

1 Answer 1

1

How about:

constraint CheckNumber_type_constr
    check ((PaymentType = 'Check') or (CheckNumber is null))

If you want to ensure that CheckNumber not null for checks as well:

constraint CheckNumber_type_constr
    check ((PaymentType = 'Check' and CheckNumber is not null) or
           (PaymentType <> 'Check' and CheckNumber is null)
          )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.