检查SQL中的约束

时间:2017-06-13 15:28:20

标签: sql-server

我希望不允许我的数据库用户输入比2017-03-18更大的日期。如何将此约束添加到我的表中? 它是否正确?

(Year([ContractEnd])<2017) and (Month([ContractEnd])<03) and (Day([ContractEnd])<18)

2 个答案:

答案 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')