检查Oracle中约束中的时间戳

时间:2016-03-04 20:30:23

标签: sql oracle constraints ddl

我创建了一个简单的表格:

CREATE TABLE Messages
(   msgID   number(10) PRIMARY KEY,
    sender_ID   number(10),
    time_sent   TIMESTAMP,
); 

现在我想为它添加一个约束,以确保发送的时间将在2014年之后。我写道:

alter table Messages
add constraint year_check 
check (time_sent > to_timestamp('2014-12-31 23:59:59'));

但是我收到以下错误:

  

ORA-30075:TIME / TIMESTAMP WITH TIME ZONE文字必须在CHECK约束中指定

我不想在我的时间戳中设置TIME ZONE并插入如下值:

INSERT INTO Messages VALUES(1, 1, TIMESTAMP '2014-12-24 07:15:57');

如何修复我的约束以使此错误消失?

2 个答案:

答案 0 :(得分:1)

当您查找错误消息in the manual时,您会看到建议:

  

操作:仅将时间或时间戳用于时区文字。

to_timestamp('2014-12-31 23:59:59')返回timestamp(没有时区),但Oracle在检查约束中需要timezone with time zone(尽管我不得不承认我不理解为什么

您可以使用已解析为timestamp with time zone的ANSI时间戳文字:

alter table Messages
  add constraint year_check 
  check (time_sent > timestamp '2014-12-31 23:59:59');

或使用具有明确时区的to_timestamp_tz

alter table Messages
  add constraint year_check 
  check (time_sent > to_timestamp_tz('2014-12-31 23:59:59 +00:00', 'YYYY-MM-DD HH:MI:SS TZH:TZM'));

顺便说一下:我宁愿在1月1日更改条件以使用>=

alter table Messages
  add constraint year_check 
  check (time_sent >= timestamp '2015-01-01 00:00:00');

否则,您可以添加2014-12-31 23:59:59.567

答案 1 :(得分:0)

尝试使用格式掩码:

select to_timestamp('2014-12-31 23:59:59') timest from dual
  2  /
select to_timestamp('2014-12-31 23:59:59') timest from dual
                *
ERROR at line 1:
ORA-01843: not a valid month

select to_timestamp('2014-12-31 23:59:59', 'YYYY-MM-DD HH24:MI:SS') timest from dual
  2  /

TIMEST
---------------------------------------------------------------------------
31-DEC-14 11.59.59.000000000 PM
相关问题