如何验证这些列?

时间:2019-02-09 12:55:03

标签: sql sql-server validation

我正在使用数据库,我需要验证“付款”模式下的某些列。

就像不使用信用卡付款一样,应将CreditCardNumber,CardHoldersName和CreditCardExpDate设置为NULL。如果使用信用卡,则CreditCardExpDate值应大于PaymentDate PaymentDue可以为NULL,但不得大于PaymentAmount

我已经在网上搜索过,但是得到的是复杂的触发器和过程,它们并没有真正的帮助。

  create table Payment.Payments(
  Payment_ID int identity (200, 21),
  Payment_Amount money constraint chk_Payment_Amount check (Payment_Amount > 
  '0'),
  Payment_Date date, -- is to be greater than the end date which is on another table
  Credit_Card_Number int,
  Card_Holders_Name char (50),
  Credit_Card_Expiry_Date date, 
  Project_ID int Foreign Key references ProjectDetails.Projects(Project_ID),
  Payment_Due money -- should not be greater than Payment Amount but 
  can still accept null*
   );

注释显示了我当前遇到的验证问题。

我为payment_date创建了一个触发器,但是我只能在插入的日期大于当前日期时触发它,如果它小于结束日期(结束日期在另一个表上),我就需要它触发

创建触发器付款日期     关于付款     插入     如       DECLARE @ModifiedDate日期       SELECT @ModifiedDate = Payment_Date从插入           IF(@ModifiedDate> getdate())           开始             PRINT'修改日期应为当前日期。因此,无法插入。”             回滚交易           结束

1 个答案:

答案 0 :(得分:0)

我在这里在两行之间读了很多书,但我认为这是您要追求的(注意,尽管我使用了CornerRadius模式):

dbo

对卡号数据类型的注释:

信用卡号的数据类型USE Sandbox; GO CREATE TABLE dbo.Payments ( Payment_ID int identity(200, 21), Payment_Amount money CONSTRAINT chk_Payment_Amount CHECK (Payment_Amount > '0'), Payment_Date date, Credit_Card_Number char(19), --note datatype change from int to char. See my comment below (copied from my comment) Card_Holders_Name varchar (50), --note I've used varchar instead. Names aren't all 50 characters long Credit_Card_Expiry_Date date, --Project_ID int FOREIGN KEY REFERENCES ProjectDetails.Projects(Project_ID) --Commented out as I don't have this table Payment_Due money CONSTRAINT chk_Payment_Due CHECK (Payment_Due > '0' OR Payment_Due IS NULL) ); GO --Credit Card format validation ALTER TABLE dbo.Payments ADD CONSTRAINT ck_Credit_Card CHECK (Credit_Card_Number LIKE '[0-9][0-9][0-9][0-9] [0-9][0-9][0-9][0-9] [0-9][0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' OR Credit_Card_Number IS NULL); --Add card details must be there, or none. ALTER TABLE dbo.Payments ADD CONSTRAINT ck_Card_Details CHECK ((Credit_Card_Number IS NULL AND Card_Holders_Name IS NULL AND Credit_Card_Expiry_Date IS NULL) OR (Credit_Card_Number IS NOT NULL AND Card_Holders_Name IS NOT NULL AND Credit_Card_Expiry_Date IS NOT NULL)) GO DROP TABLE dbo.Payments; 有点矛盾。 int的最大值为2,147,483,647,并且卡号由4组4位数字的号码(即int)组成。即使是数字,也远远高于9999 9999 9999 9999的最大值。我建议使用int并对格式进行限制。