alter table使用case语句添加约束?

时间:2014-05-23 13:40:52

标签: sql constraints oracle-apex check-constraints case-statement

我正在APEX工作,为用户预订建筑物。我正在尝试向number_guests列添加ckecks,以便根据日期和建筑物编号,用户只能输入一定数量的客人(阵亡将士纪念日和劳动节之间为10,对于此特定建筑,任何其他时间为20)。 case语句工作正常,只是当我把它与check语句放在一起时。我一直收到“缺少表达式”错误消息。请帮忙!这就是我所拥有的:

    SELECT 
    CASE

    WHEN TRIM(TO_CHAR(reserve_date,'ww')) >= '21' 
    and TRIM(TO_CHAR(reserve_date,'ww')) <= '35' 
    and TRIM(building_number) = '25'
    THEN CHECK (number_guests  <= 10)

    WHEN TRIM(TO_CHAR(reserve_date,'ww')) < '21'  
    and TRIM(building_number) = '25'
    THEN CHECK (number_guests  <= 20)

    WHEN TRIM(TO_CHAR(reserve_date,'ww')) > '35' 
    and TRIM(building_number) = '25'
    THEN CHECK (number_guests  <= 20)

    ELSE RAISERROR (N'The number of guests is invalid.')
    END
    FROM SOMERSET_RESERVATION;

1 个答案:

答案 0 :(得分:0)

check constraint的格式不是select语句。它是alter table语句(或直接在表定义中)。我认为这是你想要的逻辑:

alter table SOMERSET_RESERVATION
    add constraint check_InvalidNumberOfGuests
        check (number_guests <= 10 or
               (number_guests <= 20 and
                TRIM(building_number) = '25' and
                TO_CHAR(reserve_date, 'ww') not between '21' and '35'
               )
              );

请注意,ww格式返回零填充的数字,因此逻辑确实有效。 (否则,'3'会失败,但实际上会返回'03'。)