I have the following table:
CREATE TABLE [dbo].[EntityAttributeRelship]( [IdNmb] [int] IDENTITY(1,1) NOT NULL, [EntityIdNmb] [int] NOT NULL, [AttributeIdNmb] [int] NOT NULL, [IsActive] [bit] NOT NULL CONSTRAINT [DF_EntityAttributeRelship_IsActive] DEFAULT ((0)), CONSTRAINT [PK_EntityAttributeRelship] PRIMARY KEY CLUSTERED ([IdNmb] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
A portion of the data in the table looks like something this:
IdNmb EntityIdNmb AttributeIdNmb IsActive 1 22 7 0 2 22 8 0 3 22 9 0 4 22 10 1
I want to add a constraint to make sure that no one adds or updates a record to have IsActive = 1, if there is already a record for the EntityIdNmb where IsActive = 1.
How do I do this?
If you are using SQLServer you can create a clustered indexed view.
This ensures there’s only one EntityIdNmb in your table with IsActive = 1.