patternsqlMinor
Check constraint that exactly one in group has bit column set as true
Viewed 0 times
bitgroupcolumntruehasonethatconstraintcheckexactly
Problem
Let's say you have a table of addresses like the following:
I want a check constraint to enforce that there is always exactly one primary address per customer that allows me to switch primary addresses for a customer or add a new address and make that one primary.
I know I could have a constraint that not more than one is primary (allowing none to be primary) and then set all of a customer's address to not primary before inserting/updating an address to be primary. But how would I enforce that if a customer has addresses, one of them must always have IsPrimary = 1?
dbo.Address
(
AddressId INT PRIMARY KEY,
CustomerId INT,
IsPrimary BIT,
...
more typical address fields
...
)I want a check constraint to enforce that there is always exactly one primary address per customer that allows me to switch primary addresses for a customer or add a new address and make that one primary.
I know I could have a constraint that not more than one is primary (allowing none to be primary) and then set all of a customer's address to not primary before inserting/updating an address to be primary. But how would I enforce that if a customer has addresses, one of them must always have IsPrimary = 1?
Solution
You can define a filtered index on the table which will do this for you, there is no need to use a check constraint or an additional table for this.
Here is a good link of filtered indexes that should help you:
https://msdn.microsoft.com/en-us/library/cc280372.aspx
CREATE UNIQUE INDEX IX_Address_UniquePrimaryAddress
ON dbo.Address(CustomerId)
WHERE IsPrimary = 1;Here is a good link of filtered indexes that should help you:
https://msdn.microsoft.com/en-us/library/cc280372.aspx
Code Snippets
CREATE UNIQUE INDEX IX_Address_UniquePrimaryAddress
ON dbo.Address(CustomerId)
WHERE IsPrimary = 1;Context
StackExchange Database Administrators Q#146873, answer score: 5
Revisions (0)
No revisions yet.