Question:
I want to add a unique constraint on a mapping table (n:n).
I want that new values may be inserted, but only if TEST_FK_UID, TEST_DateFrom and TEST_DateTo are not equal to an already existing entry.
The problem is the status field.
Status 1 means active..
Status != 1 means inactive/deleted..
.
.
So one may of course insert a new entry with the same FK, DateFrom and DateTo, IF – and only if – the status of the existing entry (all existing entries, as you can insert, delete, insert, delete, insert, delete, etc.) is != 1
Here is what I have so far:
CREATE TABLE dbo._________Test
(
TEST_UID uniqueidentifier NOT NULL
,TEST_FK_UID uniqueidentifier NOT NULL
,TEST_DateFrom DateTime NOT NULL
,TEST_DateTo DateTime NOT NULL
,TEST_Status int NOT NULL
,UNIQUE(TEST_FK_UID, TEST_DateFrom, TEST_DateTo, TEST_Status)
);
It is very possible, like this
(basic credit goes to: https://stackoverflow.com/users/103075):
Edit:
OK, pedantically seen it’s not a unique constraint, it’s a check constraint, but WTF – it has the same effect and works on SQL-Server 2005 as well, and the (conditional) condition is configurable per customer (replace SET @bNoCheckForThisCustomer = ‘false’ with a select to a configuration table) – that’s not possible with a unique index AFAIK … 😉
Note this line:
(ZO_RMMIO_UID is the unique primary key of the n:n mapping table)
It’s important, since a check constraint seems to be similar to a onAfterInsert trigger.
If this line is missing, it checks on itselfs as well, which leads to the function always returning true…
And here a test case: