在SQL Server数据库中应用自定义约束

时间:2012-12-18 05:27:27

标签: sql-server-2008

我在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的所有行,只有一行可以Show_Status = True,其他所有行都必须为假。

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

1 个答案:

答案 0 :(得分:1)

如果我正确理解要求,可以使用filtered indexes

来实现
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)