SQL Server conditional CHECK constraint

社会主义新天地 提交于 2019-12-22 11:33:54

问题


I'm using 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. 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. The second constraint should prevent the sum of PaymentTotal and CreditTotal from being greater than 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).

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.


回答1:


You have written an aggregate function (SUM()) with no parameters.

"The second constraint should prevent the sum of PaymentTotal and CreditTotal from being greater than 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



回答2:


...
ADD CHECK (
    PaymentTotal + CreditTotal <= InvoiceTotal
)


来源:https://stackoverflow.com/questions/8080823/sql-server-conditional-check-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!