[英]Check Constraint SQL
I have 2 columns in a table - 我在表格中有2列-
[SendDate] and [PayDate] [SendDate]和[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 基本上用简单的话来说,如果SendDate为NULL,则PayDate无法包含值;或者如果IF SendDate为NULL,则用户输入PayDate内容时,会出现错误
I am not sure how to go on about it. 我不确定该如何进行。
Any suggestions much appreciated, thanks 任何建议,不胜感激,谢谢
Use a Check
constraint like this 使用这样的
Check
约束
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.