Date ranges unique constraint in Database

时间:2017-06-12 16:50:20

标签: sql oracle db2

I have a table "holidays" which represents people's holidays. It contains a FK to a person table, a from date column and a to date column. I want to add a constraint so that no person can have an over lapping holiday with themselves. So if Billy has a skiing holiday from 15th Jan - 20thJan, he can't have another vacation on the 18th Jan? But it's fine for him to do it on the 21st Jan?

Is this possible to do at database level via a constraint?

DB2 or Oracle can suffice?

Thanks

3 个答案:

答案 0 :(得分:2)

在DB2中,您可以使用Temporal Tables和Time Travel Queries - 查看doumentation

将业务时间与业务周期一起使用时间表将允许定义一个强制周期不重叠的索引

CREATE UNIQUE INDEX I_vacation ON vacation (person, BUSINESS_TIME WITHOUT OVERLAPS)

答案 1 :(得分:1)

Not directly. Constraints (at least in Oracle, I can't speak for other databases) work on one row at a time, they don't look at other rows - EXCEPT the UNIQUE constraint which looks across rows.

So - two solutions. One is, instead of storing ranges, to store one row per holiday DAY. (By the way, I believe what you call "holiday" is called "vacation", at least in America; "holiday" is reserved for common holidays, the same for all people, such as New Year or Christmas, etc.) In this arrangement, add a UNIQUE constraint on (person_id, vacation_day). Then re-work your input and reporting apps to translate from ranges to individual days, and respectively from individual days back to ranges.

The other solution, if you must store ranges, is to create a materialized view with refresh on commit (preferably fast refresh if the conditions permit), which shows person_id and vacation_day, one row per day - and put a UNIQUE constraint on the materialized view.

答案 2 :(得分:1)

您可以创建一个存储过程,其中包含当前行的datestart和dateend,并使用此过程的参数。如果表中存在错误的范围,则此过程返回1,否则返回0.然后在此结果过程= 0时创建约束检查