SQL Server 条件 CHECK 约束
我正在使用 SQL Server 2008 Management Studio。以下是我必须写的内容,我对第二个约束有一些困难。这让我有点困惑,我真的很感激一些帮助。
编写一条 ALTER TABLE 语句,向 AP 数据库的 Invoices 表添加两个新的检查约束。第一个应该允许 (1) 仅当 PaymentTotal 为零时 PaymentDate 为空;(2) 仅当 PaymentTotal 大于零时 PaymentDate 不为空。第二个约束应防止 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)
)
先感谢您。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经编写了一个不带参数的聚合函数 (
SUM()
)。“第二个约束应该防止 PaymentTotal 和 CreditTotal 之和大于 InvoiceTotal。”这对我来说有点令人困惑,但你应该将其更改为:
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: