Unique Constraint for Bit Column Allowing Only 1 True (1) Value

情到浓时终转凉″ 提交于 2019-12-06 06:02:30

问题


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


来源:https://stackoverflow.com/questions/47141834/unique-constraint-for-bit-column-allowing-only-1-true-1-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!