3

我有下表 Goods_In_Wagon(Goods_ID,Wagon_ID,Total_Weight)。我需要创建一些 if 语句检查约束,上面写着

“如果 WAGON_ID 介于 90 和 99 之间,那么 Total_Weight 必须大于 10。” “如果 WAGON_ID 介于 100 和 110 之间,那么 Total_Weight 必须大于 20。” “如果 WAGON_ID 介于 111 和 120 之间,那么 Total_Weight 必须大于 30。”

这在 SQL Oracle 中是否可能,如果是我该如何实现它

4

2 回答 2

6

使用离线约束:

CREATE TABLE Goods_In_Wagon (
  Goods_ID NUMBER(whatever),
  Wagon_ID NUMBER(whatever),
  Total_Weight NUMBER(whatever),
  CONSTRAINT Check_WagID_Weight
    CHECK (Wagon_ID NOT BETWEEN 90 AND 99 OR Total_Weight > 10)
)

如果不在90 和 99 之间,则约束通过Wagon_ID。如果介于 90 和 99 之间,则必须大于 10。Total_Weight

像这样的离线约束允许您在行级别应用约束逻辑,这意味着它可以使用任何列值。


附录以下是如何处理范围为Wagon_ID和的更新问题Total_Weight。可能还有其他方法,但这感觉像是“最干净的”,这意味着我个人最容易阅读:)

CREATE TABLE Goods_In_Wagon(
  Goods_ID NUMBER(whatever),
  Wagon_ID NUMBER(whatever),
  Total_Weight NUMBER(whatever),
  CONSTRAINT Check_WagID_Weight
    CHECK (
      (Wagon_ID < 90) OR
      (Wagon_ID BETWEEN 90 AND 99 AND Total_Weight > 10) OR
      (Wagon_ID BETWEEN 100 AND 110 AND Total_Weight > 20) OR
      (Wagon_ID BETWEEN 111 AND 120 AND Total_Weight > 30) OR
      (Wagon_ID > 120)
    )
)
于 2013-05-06T14:35:03.137 回答
2

经修订以反映额外要求

CREATE TABLE Goods_In_Wagon
(
    Goods_ID
    ,Wagon_ID
    ,Total_Weight
    CONSTRAINT check_Weight
    CHECK ( 
        WAGON_ID < 90
        OR
        (TOTAL_WEIGHT > 10 AND WAGON_ID >= 90 AND WAGON_ID <= 99)
        OR
        (TOTAL_WEIGHT > 20 AND WAGON_ID >= 100 AND WAGON_ID <= 110)
        OR
        (TOTAL_WEIGHT > 30 AND WAGON_ID >= 111 AND WAGON_ID <= 120)
        OR
        WAGON_ID > 120
    )
)
于 2013-05-06T14:38:03.187 回答