我有下表:
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]
表中的一部分数据看起来像这样:
IdNmb EntityIdNmb AttributeIdNmb IsActive 1 22 7 0 2 22 8 0 3 22 9 0 4 22 10 1
我想添加一个约束,以确保没有人添加或更新记录以使IsActive = 1,如果已存在EntityIdNmb的记录,其中IsActive = 1.
我该怎么做呢?
如果您使用的是SQLServer,则可以创建聚簇索引视图.
CREATE VIEW dbo.VIEW_EntityAttributeRelship WITH SCHEMABINDING AS SELECT EntityIdNmb FROM dbo.EntityAttributeRelship WHERE IsActive = 1 GO CREATE UNIQUE CLUSTERED INDEX UIX_VIEW_ENTITYATTRIBUTERELSHIP ON dbo.VIEW_EntityAttributeRelship (EntityIdNmb)
这确保了表中只有一个EntityIdNmb,IsActive = 1.