【问题标题】:Checking timestamps in a constraint in Oracle在 Oracle 中检查约束中的时间戳
【发布时间】:2016-03-04 20:30:23
【问题描述】:

我创建了一个简单的表:

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');

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

【问题讨论】:

    标签: sql oracle constraints ddl


    【解决方案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

    【讨论】:

    • 我理解你的逻辑,但我仍然收到错误add constraint year_check * ERROR at line 2: ORA-02293: cannot validate (USER.YEAR_CHECK) - check constraint violated
    • @user3268401,很可能你有2015-01-01之前的现有数据。
    • @user3268401:香农是对的:您现有的数据根本无法验证。你需要先解决这个问题。
    【解决方案2】:

    尝试使用格式掩码:

    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
    

    【讨论】:

    • 您能否更清楚地说明您希望我将约束更改为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多