Vlad11
Vlad11

Reputation: 103

Check Constraint SQL

I have 2 columns in a table -

[SendDate] and [PayDate]

I am trying to implement a constraint that will check that - the product cannot be paid for if it has not been sent out.

Basically in simpler words IF SendDate is NULL then PayDate cannot containt a value or something like IF SendDate is NULL then if user types in something to PayDate, an error will rise

I am not sure how to go on about it.

Any suggestions much appreciated, thanks

Upvotes: 0

Views: 61

Answers (1)

ughai
ughai

Reputation: 9890

Use a Check constraint like this

CHECK( [PayDate] IS NULL OR ([PayDate] IS NOT NULL AND [SendDate] IS NOT NULL))

Sample

CREATE TABLE dbo.Payment
(
    [Id] INT IDENTITY(1,1) PRIMARY KEY,
    [SendDate] DATE NULL,
    [PayDate] DATE NULL,
    CONSTRAINT CHK_PayDate CHECK( [PayDate] IS NULL OR ([PayDate] IS NOT NULL AND [SendDate] IS NOT NULL))
)

-- All Fine
INSERT INTO dbo.Payment([SendDate],[PayDate]) VALUES(CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);
INSERT INTO dbo.Payment([SendDate],[PayDate]) VALUES(CURRENT_TIMESTAMP,NULL);
INSERT INTO dbo.Payment([SendDate],[PayDate]) VALUES(NULL,NULL);

--Raises Error
INSERT INTO dbo.Payment([SendDate],[PayDate]) VALUES(NULL,CURRENT_TIMESTAMP);

Upvotes: 2

Related Questions