Zeki Çelik Zeki Çelik - 3 months ago 34
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

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

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'.