简体   繁体   English

SQL Server条件检查约束

[英]SQL Server conditional CHECK constraint

I'm using SQL Server 2008 Management Studio. 我正在使用SQL Server 2008 Management Studio。 Below is what I have to write, and I'm having some difficulties for the second constraint. 以下是我必须写的内容,对于第二个约束,我遇到了一些困难。 It is a little bit confusing me and I would really appreciate some help. 这让我有些困惑,我将不胜感激。

Write an ALTER TABLE statement that adds two new check constraints to the Invoices table of the AP database. 编写一条ALTER TABLE语句,将两个新的检查约束添加到AP数据库的“发票”表中。 The first should allow (1) PaymentDate to be null only if PaymentTotal is zero and (2) PaymentDate to be not null only if PaymentTotal is greater than zero. 第一个应该允许(1)仅当PaymentTotal为零时,PaymentDate为空;以及(2)仅当PaymentTotal大于零时,PaymentDate不为空。 The second constraint should prevent the sum of PaymentTotal and CreditTotal from being greater than InvoiceTotal. 第二个约束应防止PaymentTotal和CreditTotal的总和大于InvoiceTotal。

Here is what I have so far, the first constraint works but not the second, (sum of the PaymentTotal and CreditTotal from being greater than InvoiceTotal). 到目前为止,这是我所拥有的,第一个约束有效,但第二个约束无效(PaymentTotal和CreditTotal的总和大于InvoiceTotal)。

ALTER TABLE Invoices WITH CHECK
ADD check (
    (PaymentTotal = 0 AND PaymentDate is NULL)
    OR
    (PaymentTotal > 0 AND PaymentDate is NOT NULL)
)
ADD CHECK (
    (PaymentTotal < InvoiceTotal = SUM)
    OR
    (CreditTotal < InvoiceTotal = SUM)
)

Thank you in Advance. 先感谢您。

You have written an aggregate function ( SUM() ) with no parameters. 您编写了没有参数的聚合函数( SUM() )。

"The second constraint should prevent the sum of PaymentTotal and CreditTotal from being greater than InvoiceTotal." “第二个约束应防止PaymentTotal和CreditTotal的总和大于InvoiceTotal。” This is a bit confusing to me, but here's what you should change it to: 这让我有些困惑,但是您应该将其更改为:

ALTER TABLE Invoices WITH CHECK 
ADD check ( 
    (PaymentTotal = 0 AND PaymentDate is NULL) 
    OR 
    (PaymentTotal > 0 AND PaymentDate is NOT NULL) 
) 
go

ALTER TABLE Invoices WITH CHECK
ADD CHECK ( 
    (PaymentTotal + CreditTotal) <= InvoiceTotal 
) 
go
...
ADD CHECK (
    PaymentTotal + CreditTotal <= InvoiceTotal
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM