SQL Server检查空值

时间:2014-01-21 00:49:24

标签: sql

我有一个表,我正在添加一个约束,所以如果PaymentType不同于'Check',以确保CheckNumber为null。这是我的表:

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)
    )
);

所以,我试过了

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

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

两者都惨遭失败......

1 个答案:

答案 0 :(得分:1)

怎么样:

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

如果您想确保CheckNumber也不为null检查:

constraint CheckNumber_type_constr
    check ((PaymentType = 'Check' and CheckNumber is not null) or
           (PaymentType <> 'Check' and CheckNumber is null)
          )