-3

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 ?

enter image description here

user3749816
  • 77
  • 1
  • 1
  • 7
  • Can there be a duplicate of PK 7 with AddressId=102, Primary=FALSE, EndDate = 12/31/9999? – Tah May 08 '17 at 18:31
  • Yes there can be duplicates with different PK – user3749816 May 08 '17 at 18:32
  • 1
    Please read http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557 and the accepted answer –  May 08 '17 at 19:42

2 Answers2

0

You want to create a unique constraint on the 3 columns: AddressID, Primary, EndDate.

ALTER TABLE [YourTableName]
ADD CONSTRAINT [UniqueConstraintName] UNIQUE (AddressID, Primary, EndDate);
Tah
  • 1,526
  • 14
  • 22
0

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'
Eli
  • 2,538
  • 1
  • 25
  • 36