0

我有一个表,其中存储了带有列的付款详细信息:(paymentmethod- 支票、现金或信用卡)、( Checknumber)、( Cardholdersname)、( creditcardnumber)。

问题是:我如何验证 when paymentmethodiscash或 check then应该留空,而 when Cardholdersnameis then应该留空。creditcardnumberpaymentmethodcreditcardChecknumber

4

1 回答 1

1

你真的有两个不同的表:

PaymentDetails(ID, PaymentMethod) and
CreditCardDetails (PaymentDetailsID, CardholderName, CreditCardNumber)

两个表中的所有列都不可为空。


可以将所有三个案例保存在同一个表中。在这种情况下,请尝试以下操作:

CREATE TABLE [dbo].[PaymentDetails]
(
    ID INT IDENTITY(1,1) NOT NULL,
    PaymentMethod INT NOT NULL CHECK (PaymentMethod IN (1,2,3)), -- Cash, Check, Credit
    CheckNumber int NULL,
    CardHoldersName nvarchar(100) NULL,
    CreditCardNumber varchar(20) NULL
)

ALTER TABLE [dbo].[PaymentDetails]
    ADD CONSTRAINT [PaymentTypeConstraint] 
    CHECK  ((PaymentMethod = 1 AND CheckNumber IS NULL AND 
                                   CardholdersName IS NULL AND
                                   CreditCardNumber IS NULL) OR
            (PaymentMethod = 2 AND CheckNumber IS NOT NULL AND 
                                   CardholdersName IS NULL AND
                                   CreditCardNumber IS NULL) OR
            (PaymentMethod = 3 AND CheckNumber IS NULL AND 
                                   CardholdersName IS NOT NULL AND
                                   CreditCardNumber IS NOT NULL));
于 2012-08-25T23:24:57.320 回答