我希望不允许我的数据库用户输入比2017-03-18
更大的日期。如何将此约束添加到我的表中?
它是否正确?
(Year([ContractEnd])<2017) and (Month([ContractEnd])<03) and (Day([ContractEnd])<18)
答案 0 :(得分:3)
您可以像这样在现有表中添加这样的约束:
alter table t add constraint chk_ContractEnd_lt_20170319
check (ContractEnd<'20170319');
rextester演示:http://rextester.com/FQWFMI88817
create table t (
id int not null identity(1,1)
, ContractEnd date
/* at table creation */
, constraint chk_ContractEnd_lt_20170319 check (ContractEnd<'20170319')
)
alter table t drop constraint chk_ContractEnd_lt_20170319;
/* to existing table */
alter table t add constraint chk_ContractEnd_lt_20170319
check (ContractEnd<='20170318');
insert into t values ('20161231')
insert into t values ('20170318')
/* all good */
insert into t values ('20170319')
/* -- Error, constraint violation */
答案 1 :(得分:0)
尝试
[ContractEnd] DATE CHECK ([ContractEnd] <= '20170318')