Unique Constraint for Bit Column Allowing Only 1 T

2019-05-10 04:19发布

问题:

I have this table:

CREATE TABLE [tblExample](
    [ExampleID] [int] IDENTITY(1,1) NOT NULL,
    [WordsAndStuff] [nvarchar](max) NOT NULL,
    [Active] [bit] NOT NULL

I want the Active column to have a unique constraint that will only allow one record to be true (1). At this point, I don't need there to BE a true record all the time, there just cannot be more than one of them.

How do I write the constraint?

回答1:

Just one active record at a time in the table? You can use a unique index with a filter:

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