1

I want not to allow my DB user to enter bigger dates than 2017-03-18. How can add this constraint to my table? Is this Correct?

(Year([ContractEnd])<2017) and (Month([ContractEnd])<03) and (Day([ContractEnd])<18)
4
  • What type of ContractEnd? DATETIME? Commented Jun 13, 2017 at 15:32
  • No that is not right. The values in your code don't match the date that you stated. And there is no need to break apart a date(time) like that do check. Commented Jun 13, 2017 at 15:35
  • The column type is Date. Commented Jun 13, 2017 at 15:37
  • Update: Date is 2017-03-18 Commented Jun 13, 2017 at 15:39

2 Answers 2

4

You can add a constraint like that to an existing table like so:

alter table t add constraint chk_ContractEnd_lt_20170319 
  check (ContractEnd<'20170319');

rextester demo: 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 */
Sign up to request clarification or add additional context in comments.

2 Comments

If the datatype is datetime or datetime2, then using ContractEnd < '20170102' might be necessary.
@BaconBits That's true.
0

Try

[ContractEnd] DATE CHECK ([ContractEnd]  <= '20170318')

4 Comments

I tried what you said, but here is the error: The ALTER TABLE statement conflicted with the CHECK constraint "CK_Professor". The conflict occurred in database "University", table "dbo.Professor", column 'ContractEnd'.
@kwram Of course, you should remove previous constraint with name CK_Professor. After that use alter table Professor add constraint . do you know how to remove it?
You are right, but I haven't already set any constraint on this column! I don't have a constraint on this column.
@kwram no, you have according to the error message. Check SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'CK_Professor') AND parent_object_id = OBJECT_ID(N'Professor')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.