Chris
Chris

Reputation: 8412

T-SQL: CHECK constraint not working

I have the following T-SQL schema. The problem I am having is that the check constraint on the Download table is not working. I am still able to insert records into that table that contain NULL values for both ProductId and CategoryId. Why is this so?

I want both the ProductId and CategoryId columns to allow NULL values, but for any given record only one of these are allowed to be set to NULL, the other needs to be a corresponding Id of the Category or Product table.

CREATE TABLE Category (
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Description nvarchar(100) NULL,
    ParentCategoryId int NULL
    CONSTRAINT fk_CategoryId_CategoryId FOREIGN KEY (Id) REFERENCES Category(Id)
)
GO

CREATE TABLE Product (
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Title nvarchar(100) NOT NULL,
    TagLine nvarchar(MAX) NOT NULL,
    Description nvarchar(MAX)NULL,
    CategoryId int NOT NULL,
    ImageUrl nvarchar(255) NULL,
    Keywords nvarchar(200) NOT NULL

    CONSTRAINT fk_ProductCategoryId_CategoryId FOREIGN KEY (CategoryId) REFERENCES Category(Id)
)
GO

CREATE TABLE Download (
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Title nvarchar(100) NOT NULL,
    Description nvarchar(MAX) NULL,
    CategoryId int NULL,
    ProductId int NULL,
    DownloadUrl nvarchar(255) NOT NULL,

    CONSTRAINT fk_DownloadCategoryId FOREIGN KEY (CategoryId) REFERENCES Category(Id),
    CONSTRAINT fk_DownloadProductId FOREIGN KEY (ProductId) REFERENCES Product(Id),
    CONSTRAINT chk_ReferencesCategoryOrProduct CHECK (ProductID != NULL AND CategoryId != NULL)
)
GO

Upvotes: 2

Views: 2019

Answers (1)

OMG Ponies
OMG Ponies

Reputation: 332521

Use:

CONSTRAINT chk_ReferencesCategoryOrProduct CHECK (ProductID IS NOT NULL 
                                               OR CategoryId IS NOT NULL)

NULL isn't a value -- it's a placeholder for the lack of a value. Which is why you need to use specific syntax to check for it.

Upvotes: 7

Related Questions