Vishwajeet
Vishwajeet

Reputation: 1683

Apply Customize constraint in SQL Server database

I have the following table in 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)
    )

In this I want to apply a customize constraint like, at one time only two rows can have Show_Status to be true. One with BannerIsDomestic = true and one with BannerIsDomestic = false.

For all the rows that have BannerIsDomestic = true only one can have Show_Status = True and all other must be false.

And for all the rows that have BannerIsDomestic = false only one can have Show_Status = True, all others must be false.

Can I do this in SQL Server?

Upvotes: 1

Views: 64

Answers (1)

8kb
8kb

Reputation: 11406

If I am understanding the requirements correctly, this should be achievable with 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) 

Upvotes: 1

Related Questions