Click here to Skip to main content
14,734,364 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I would like to set a CHECK or DEFAULT constraint to ensure that a Date2 is always equal to Date1 + 5 days.

My problem is that I can't do operations with a DATE value and an INT value

What I have tried:

ALTER TABLE TableName
ADD CONSTRAINT DF_Date2_ExpiringDate DEFAULT Date1 +30 FOR Date2;


ALTER TABLE TableName
ADD CONSTRAINT CK_TableName_Date2Is30DaysAfterDate1
        CHECK (Date2= Date1+ 30);
Posted
Updated 4-Nov-20 4:41am

1 solution

If Date2 is always five days after Date1, then you don't need to store Date2 at all. Just use a computed column.
ALTER TABLE TableName
DROP COLUMN Date2;

ALTER TABLE TableName
ADD Date2 As (DateAdd(day, 5, Date1));
Specify Computed Columns in a Table - SQL Server | Microsoft Docs[^]

As per your previous question[^], if you ever need Date2 to be anything other than Date1 + 5 days, you cannot add a CHECK constraint to your table.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900