SQL Constraint: date A is before date B — How?

时光毁灭记忆、已成空白 提交于 2020-01-09 07:54:09

问题


I'm creating an SQL table that needs the fields from=date and to=date but I'd like to make a constraint so that to cannot be before from. My program will check for it but I'd like to learn how to enforce it with SQL. I've written SQL before but never really used constraints and don't know how they work.

So the question is: Using standard SQL, how do I make sure that From is before To?


回答1:


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

Or if you need to apply this to an existing table, use:

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

The PostgreSQL manual contains a good chapter about check constraints: http://www.postgresql.org/docs/current/static/ddl-constraints.html#AEN2410




回答2:


I think this is ok for sql server, mysql and oracle

ALTER TABLE myTbl
ADD CONSTRAINT chk_Dates CHECK (dtFrom < dtTo)


来源:https://stackoverflow.com/questions/13732269/sql-constraint-date-a-is-before-date-b-how

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!