Oracle只有时间限制

时间:2018-02-15 08:42:50

标签: oracle

我有两列start_timeend_time。类型为DATE

我想制定一个约束,使start_time低于end_time。日期部分无关紧要。 所以如果这两个变量是: 开始时间:2017-01-02 11:40 结束时间:2017-01-01 12:40

返回True

我该怎么做?

2 个答案:

答案 0 :(得分:3)

其中一个日期格式掩码为'sssss',它提供午夜后的秒数。所以你可以强制执行你的约束:

 alter table your_table 
    add constraint start_end_range_ck as 
    check (to_number(to_char(start_date, 'sssss')) < to_number(to_char(end_date, 'sssss')))
/

或者你想<=,你的问题不清楚。

答案 1 :(得分:1)

有多种方法可以做到这一点;我喜欢APC的sssss方法,但蒂姆关于使用字符串的建议也有效:

check (to_char(start_time, 'HH24:MI:SS') < to_char(end_time, 'HH24:MI:SS'))

或者你可以通过从自身中减去截断值来获得每天的小数部分(这实际上为你提供了两个数字,它们是APC&#39;的1/8400):

check (start_time - trunc(start_time) < end_time - trunc(end_time))

如果您真的想将它们视为日期,可以将这些数字添加回名义日期:

check (date '1900-01-01' + (start_time - trunc(start_time))
  < date '1900-01-01' + (end_time - trunc(end_time)))

或根据它们之间的差异修改一个值日期部分,这可能最接近您(可能错放)避免类型转换的愿望:

check_times check (start_time + (trunc(end_time) - trunc(start_time)) < end_time)

或者,如果你真的想要明确,你可以拉出每个时间元素并单独比较它们:

check (
  extract(hour from cast(start_time as timestamp)) < extract(hour from cast(end_time as timestamp))
  or (
    extract(hour from cast(start_time as timestamp)) = extract(hour from cast(end_time as timestamp))
    and extract(minute from cast(start_time as timestamp)) < extract(minute from cast(end_time as timestamp))
  )
  or (
    extract(hour from cast(start_time as timestamp)) = extract(hour from cast(end_time as timestamp))
    and extract(minute from cast(start_time as timestamp)) = extract(minute from cast(end_time as timestamp))
    and extract(second from cast(start_time as timestamp)) < extract(second from cast(end_time as timestamp))
  )
)

但这显然开始变得有点傻了,而且仍然会进行类型转换,因为你必须将日期转换为时间戳,以便能够首先提取时间组件......