For below table,
How to add a Constraint in SQL to enforce a maximum of one AddressID has Primary = TRUE where EndDate = 12/31/9999 ?
For below table,
How to add a Constraint in SQL to enforce a maximum of one AddressID has Primary = TRUE where EndDate = 12/31/9999 ?
You want to create a unique constraint on the 3 columns: AddressID, Primary, EndDate.
ALTER TABLE [YourTableName]
ADD CONSTRAINT [UniqueConstraintName] UNIQUE (AddressID, Primary, EndDate);
What you need here is a unique index, not a constraint; an index can be filtered, though a constraint cannot. Please try the index creation script below and let me know how it goes.
Another point, you have a field named PRIMARY which is a reserved word in SQL Server; while you are able to circumvent syntactical issues by enclosing the field name in square brackets (as I did in the index script below) you would want to try to avoid that naming convention if at all possible.
CREATE UNIQUE INDEX idx_max_address_id
ON myTable (PK, AddressId)
WHERE [PRIMARY] = 'TRUE'
AND EndDate = '12/31/9999'