位列的唯一约束仅允许1个真(1)值

cra*_*mmy 4 t-sql sql-server constraints unique

我有这张桌子:

CREATE TABLE [tblExample](
    [ExampleID] [int] IDENTITY(1,1) NOT NULL,
    [WordsAndStuff] [nvarchar](max) NOT NULL,
    [Active] [bit] NOT NULL
Run Code Online (Sandbox Code Playgroud)

我希望Active列具有唯一约束,该约束只允许一条记录为真(1).在这一点上,我不需要一直是一个真正的记录,只是不能超过其中一个.

我该如何编写约束?

Sql*_*Zim 6

active表中一次只有一条记录?您可以使用带过滤器的唯一索引:

create unique nonclustered index uixf_tblExample_Active_filtered
  on tblExample (Active)
    include (ExampleId, WordsAndStuff) -- optional included columns
  where Active=1
Run Code Online (Sandbox Code Playgroud)