Zeki Çelik Zeki Çelik - 15 days ago 7
SQL Question

sql check constraint age from birthdate

How can I have a check constraint for

age < 40 from birthdate
when creating a table?
Something like:

SELECT DATEDIFF(yy,” Birthdate ”, getdate()) as age
age<40


Then how could I have another check constraint when creating table and counting an attribute, grouping it and checking if it's > 6?

Such as below but as a check constraint?

select count(attributex) as counter from entityx
group by attributex
having counter>6

Answer
create table person (Birthdate date check (DATEDIFF(year,Birthdate,getdate()) < 40))

insert into person (Birthdate) values ('1990-01-01');

(1 row(s) affected)

insert into person (Birthdate) values ('1970-01-01');

Msg 547, Level 16, State 0, Line 7
The INSERT statement conflicted with the CHECK constraint "CK__person__Birthdat__30F848ED". The conflict occurred in database "dmarkovitz", table "dbo.person", column 'Birthdate'.

Comments