SQL约束:日期A在日期B之前 - 如何?

时间:2012-12-05 20:56:08

标签: sql constraints

我正在创建一个需要字段 from = date to = date 的SQL表,但是我想制定一个约束,以便不能在之前。我的程序将检查它,但我想学习如何使用SQL强制执行它。 我之前编写过SQL,但从未真正使用过约束,也不知道它们是如何工作的。

所以问题是:使用标准SQL,如何确保 From To 之前?

2 个答案:

答案 0 :(得分:12)

create table foo
(
   from_date date,
   to_date date,
   constraint check_dates check (from_date < to_date)
);

或者,如果您需要将其应用于现有表格,请使用:

alter table foo
   add constraint check_dates check (from_date < to_date);

PostgreSQL手册包含一个关于检查约束的好章节:http://www.postgresql.org/docs/current/static/ddl-constraints.html#AEN2410

答案 1 :(得分:0)

我认为这对于sql server,mysql和oracle

是可以的
ALTER TABLE myTbl
ADD CONSTRAINT chk_Dates CHECK (dtFrom < dtTo)