添加特殊约束以避免出现这种情况的重复行?

Add special constraint to avoid duplicate rows with this condition?

我有一个 table 看起来像这样:

ClientId  FloorNum   BedNum   IsActive
11        2          212      1        
12        2          214      0        
12        2          214      1        
13        2          215      0        
13        2          215      0        
13        2          215      0        
13        2          215      0        
13        2          215      1        
12        2          215      1        

如您所见,FloorNum/BedNum 组合 2/215 有两行,其中 IsActive 等于 1。这不可能发生。

另一方面,一个 FloorNum/BedNum 组合可以有很多行,其中 IsActive 等于 0。

如何向 table 添加约束,以便 FloorNum/BedNum 组合只能有一行 IsActive = 1?

感谢任何帮助。

您可以使用 WHERE 子句创建 a filtered unique index

CREATE UNIQUE NONCLUSTERED INDEX IX_[index name]_FloorNum_BedNum ON [myTable] (
    FloorNum ASC,
    BedNum ASC)
WHERE (IsActive = 1)

这只会考虑 IsActive 列设置为 1 的记录。

根据您的描述,我认为 ClientId 在此示例中不是必需的,但如果我错了,您也可以将其添加到索引中。

您可以在 table 上添加 Trigger 来检查此条件。

create TRIGGER tr_check_unique ON YourTable
FOR INSERT
AS
    declare @FloorNum int;
    declare @BedNum int;

    select @FloorNum=i.FloorNum from inserted i;    
    select @BedNum=i.BedNum from inserted i;    

begin try
        if exists(select FloorNum  ,BedNum  from YourTable
        where FloorNum=@FloorNum and BedNum=@BedNum and IsActive=1)

        raiserror ('',16,1)
end try

begin catch
raiserror ('record is not unique',16,1)
end catch