我正在使用SQL Server 2008 Management Studio。下面是我要编写的内容,我对第二个约束有一些困难。这有点令我困惑,我真的很感激一些帮助。
编写一个ALTER TABLE语句,该语句将两个新的检查约束添加到AP数据库的Invoices表中。第一个应该允许(1)PaymentDate仅在PaymentTotal为零时为空,并且(2)PaymentDate仅在PaymentTotal大于零时不为空。第二个约束应该防止PaymentTotal和CreditTotal的总和大于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)
)
先谢谢你。
答案 0 :(得分:3)
您编写了一个没有参数的聚合函数(SUM()
)。
“第二个约束应该防止PaymentTotal和CreditTotal的总和大于InvoiceTotal。”这对我来说有点混乱,但是你应该把它改成:
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
答案 1 :(得分:2)
...
ADD CHECK (
PaymentTotal + CreditTotal <= InvoiceTotal
)