2016-11-19 160 views
0

如何在创建表时对age < 40 from birthdate设置检查约束? 喜欢的东西:从出生日期开始sql check约束的年龄

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

然后,我怎么可能有另一个检查约束创建表时计数的属性,它的分组和检查,如果是“6?

如下面但作为检查约束?创建表时

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

我删除了不兼容的数据库标记。你有MySQL和Oracle,但代码是SQL Server。 –

回答

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

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

(1行(一个或多个)受影响)

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

Msg 547,级别16,状态0,行7
INSERT语句与CHECK约束“CK__person__Birthdat__30F848ED”冲突。冲突发生在数据库“dmarkovitz”,表“dbo.person”,“出生日期”列中。

0

检查约束: http://www.w3schools.com/sql/sql_check.asp

而对于第二个问题,我想你想提出一个检查约束这将限制插入类似条件的行数(年龄> 6和年龄< 40)。为此,它更有意义检查最大限制而不是最小限定如下例所示:

CREATE TABLE EnitityX 
(
Age int NOT NULL, 
RecordId int NOT NULL AUTO_INCREMENT, 
CHECK (Age>6), 
CHECK (Age<40), 
CHECK (RecordId<6) 
) 
+0

感谢您的帮助,但我必须计算年龄作为派生attirubute,我只是生日不年龄,所以我认为@杜杜马尔科维茨的答案将解决我的问题。 – novice