我有一个表格,用于存储付款明细与列:(paymentmethod
- 包括支票,现金或信用卡),(Checknumber
),(Cardholdersname
),({ {1}})。
问题是:如何在creditcardnumber
为paymentmethod
时进行验证,或在cash
后进行检查,Cardholdersname
应留空,creditcardnumber
为{ {1}}然后paymentmethod
应留空。
答案 0 :(得分: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));