1

我在 SQL Server 中有下表

  Create Table Banners
    (
    BannerID int Identity(1,1),
    BannerUrl nvarchar(500),
    BannerIsDomestic bit,
    BannerName nvarchar(50),
    CreationDate datetime,
    ModificationDate datetime,
    Show_Status bit,
    Remark nvarchar(500)
    Constraint Banner_ID_PK Primary Key (BannerID)
    )

在此我想应用一个自定义约束,例如,一次只有两行必须Show_Status 为真。一个与BannerIsDomestic = true一个与BannerIsDomestic = false

对于所有BannerIsDomestic = true只有一个的行可以有Show_Status = True,所有其他的都必须是假的。

对于BannerIsDomestic = false只有一个 can have的所有行Show_Status = True,所有其他行都必须为 false。

我可以在 SQL Server 中执行此操作吗?

4

1 回答 1

1

如果我正确理解了要求,这应该可以通过过滤索引来实现:

CREATE TABLE Banners
    (
    BannerID int Identity(1,1),
    BannerUrl nvarchar(500),
    BannerIsDomestic bit,
    BannerName nvarchar(50),
    CreationDate datetime,
    ModificationDate datetime,
    Show_Status bit,
    Remark nvarchar(500)
    Constraint Banner_ID_PK Primary Key (BannerID)
    )

CREATE UNIQUE NONCLUSTERED INDEX IX_Banners_IsDomesticTrue 
ON Banners (BannerIsDomestic) WHERE Show_Status = 1 

INSERT Banners (BannerIsDomestic, BannerName, Show_Status) 
VALUES (1, 'DomesticBannerShow', 1), (1, 'DomesticBannerHide', 0), 
(0, 'ItnlBannerShow', 1), (0, 'IntlBannerHide', 0) 

-- This will fail
INSERT Banners (BannerIsDomestic, BannerName, Show_Status) 
VALUES (1, 'DomesticBanner2', 1)

-- This will fail
INSERT Banners (BannerIsDomestic, BannerName, Show_Status)  
VALUES (0, 'IntlBanners2', 1) 
于 2012-12-18T07:41:39.440 回答