我有一个名为'loan'的表,其约束为Loan_Date < Return_Date
。我无法在返回日期中插入空值。
构造:CONSTRAINT LOAN_DATE_CK CHECK (Loan_Date < Return_Date)
我的SQL声明:
INSERT INTO Loan (Borrower_Id, Copy_Id, Loan_Date ,Return_Date) VALUES
('00001','00001','2014-04-01','2014-04-10'),
('00001','00007','2014-04-10',' ');
错误:
****Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "LOAN_DATE_CK". The conflict occurred in database "lib_database", table "dbo.Loan".
The statement has been terminated.****
我可以输入两个值的记录。任何人都可以帮我纠正这个错误吗?
答案 0 :(得分:2)
删除约束或在约束中添加其他条件并将其添加为
CONSTRAINT LOAN_DATE_CK CHECK (Loan_Date < Return_Date OR Return_Date is null)
并按此插入
INSERT INTO Loan (Borrower_Id, Copy_Id, Loan_Date ,Return_Date) VALUES
('00001','00001','2014-04-01','2014-04-10'),
('00001','00007','2014-04-10', null); --make null value instead of ' ' or ''
答案 1 :(得分:0)
您可以将约束更改为以下内容:[未经过测试]
(Loan_Date < ISNULL(Return_Date, '9999-12-01'))
在这种情况下,如果您的返回日期为空,则会忽略它。
答案 2 :(得分:0)
我假设Loan_Date,Return_Date字段的类型为Date / DateTime - 您无法针对空值成功评估Date数据类型(2014-01-01&gt;或&lt; null)此值将始终返回false
我建议添加一个ISNULL检查条件以返回一个可以检查的静态日期
CONSTRAINT LOAN_DATE_CK CHECK (Loan_Date < ISNULL(Return_Date, CAST('CustomDate' as DATE)))