I have a table called 'DailyAllocations', which has a soft delete flag (DATETIME, NULLABLE) called 'Deleted', and the other significant column called ProcessHistoryID (INT, NULLABLE).
I need to add a contraint to the table, that will not allow a row to be soft deleted, while there is a value in the ProcessHistoryID.
ALTER TABLE dbo.DailyAllocation
ADD CONSTRAINT chk_dont_delete_processed CHECK ((Deleted IS NULL AND ProcessHistoryID IS NULL) OR (Deleted IS NOT NULL AND ProcessHistoryID IS NULL))
But even though my data is valid, it's failing when I try to apply the containt:
The ALTER TABLE statement conflicted with the CHECK constraint "chk_dont_delete_processed". The conflict occurred in database "MyDB", table "dbo.DailyAllocation".
It might be my logic, or else, I am doing something strange.
So, you can't have a deleted row, with a ProcessHistoryID. What am I doing wrong?
The following query returns no results, which means the data is currently clean:
SELECT * FROM dbo.DailyAllocation WHERE Deleted IS NOT NULL AND ProcessHistoryID IS NOT NULL
SELECT * FROM dbo.DailyAllocation WHERE Deleted IS NULL AND ProcessHistoryID IS NOT NULLquery?WHERE ProcessHistoryID IS NOT NULL. The part of constraint related toDeletedis redundant.