How to check if a DATE
being inserted
or updated
in a table
is between two other dates
from another table.
Adicional Info:
I have 2 tables
:
Activity
:
-
StartDate
date NOT NULL -
EndDate
date NULLABLE
SubActivity
:
-
SubActivityDate
date NOT NULL
When
EndDate IS NOT NULL
I check if:StartDate
≤SubActivityDate
≤EndDate
When
EndDate IS NULL
I check if:StartDate
≤SubActivityDate
I was trying to write a BEFORE INSERT trigger but I figured out that it doesnt exist.
So what I could do?
- AFTER INSERT?
- INSTEAD OF INSERT? looks better than 1st solution
- Is it possible just with CHECK Constraints?
How do I solve this problem?
EDIT
I just went with the CHECK constraint + function:
constraint:
ALTER TABLE SubActivity
ADD CONSTRAINT CK_SubActivity_Date CHECK (dbo.ufnIsSubactivityDateValid(ActivityID, SubActivityDate) = 1);
function:
CREATE FUNCTION ufnIsSubactivityDateValid(@ActivityID [int], @SubActivityDate [date])
RETURNS [bit]
AS
BEGIN
DECLARE @StartDate date, @EndDate date;
SELECT @StartDate = StartDate , @EndDate = EndDate
FROM Activity
WHERE ActivityID = @ActivityID;
IF (@SubActivityDate < @StartDate )
RETURN 0; -- out of range date
IF (@EndDate IS NULL)
RETURN 1; -- good date
ELSE
IF (@SubActivityDate > @EndDate)
RETURN 0; -- out of range date
RETURN 1; -- good date
END