patternsqlMinor
Unique Contraint/Index Based On Values
Viewed 0 times
uniquecontraintbasedvaluesindex
Problem
I have a table that has the following column definitions:
Question: I want to have a Constraint on
I've tried the normal Unique constraints, but they limit the dataset to only allow 1 record with a given
ID (INT, PK)
Name (VarChar)
Active (Bit)
Bunch_of (Other_columns)Question: I want to have a Constraint on
Name/Active such that we can only have 1 record with a given Name that is Active (Active = 1), but we could have many records that have the same Name that are Inactive (Active = 0). Is this possible?I've tried the normal Unique constraints, but they limit the dataset to only allow 1 record with a given
Name to be Inactive.Solution
To enforce this declaratively in 2005 you can use an indexed view.
CREATE VIEW dbo.ActiveNames
WITH SCHEMABINDING
AS
SELECT Name
FROM dbo.YourTable
WHERE Active = 1
GO
CREATE UNIQUE CLUSTERED INDEX UQ_ActiveNames ON dbo.ActiveNames(Name)Code Snippets
CREATE VIEW dbo.ActiveNames
WITH SCHEMABINDING
AS
SELECT Name
FROM dbo.YourTable
WHERE Active = 1
GO
CREATE UNIQUE CLUSTERED INDEX UQ_ActiveNames ON dbo.ActiveNames(Name)Context
StackExchange Database Administrators Q#21690, answer score: 8
Revisions (0)
No revisions yet.