问题
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