在SQL中创建具有空约束但具有约束的表

时间:2013-05-26 22:26:32

标签: sql constraints create-table

我想创建一个列值为> 0的表,它可以为null。

当我在创建表格列

时这样做
CREATE TABLE Ship
  (
    SITE_ID         INTEGER NOT NULL,
    Ship_CATEGORY  VARCHAR2(50)  CHECK (WRECK_CATEGORY IN ('Military','Government','Passenger', 'Unknown', 'Commercial')),
    Ship_TYPE      VARCHAR2(100) ,
    Ship_TONNAGE   INTEGER CHECK ((WRECK_TONNAGE>0) AND WRECK_TONNAGE IS NULL) ,
    Ship_CAUSE     VARCHAR2(100) NULL CHECK (WRECK_CAUSE IN ('Fire', 'Collision','Unknown',' Deliberate', 'Explosion',' Attack', 'Other')),
    Ship_DATESUNK  DATE NULL,
    Ship_CONDITION VARCHAR2(50) NULL CHECK (WRECK_CONDITION IN ('Excellent', 'Moderate','Poor', 'Very Poor')),
    CONSTRAINT SHIPWRECK_PK PRIMARY KEY (SITE_ID)
  );

在“Ship_TONNAGE INTEGER CHECK((WRECK_TONNAGE> 0)和WRECK_TONNAGE为空”行中,“ 当我向此列插入空值时,它违反了约束。我如何创建我的表满足条件?感谢

1 个答案:

答案 0 :(得分:1)

将检查约束从and更改为or

CHECK ((WRECK_TONNAGE>0) or WRECK_TONNAGE IS NULL)

您的约束引用了错误的列WRECK *而不是SHIP *。试试这个定义声明:

CREATE TABLE Ship
  (
    SITE_ID         INTEGER NOT NULL,
    Ship_CATEGORY  VARCHAR2(50)  CHECK (SHIP_CATEGORY IN ('Military','Government','Passenger', 'Unknown', 'Commercial')),
    Ship_TYPE      VARCHAR2(100) ,
    Ship_TONNAGE   INTEGER CHECK ((SHIP_TONNAGE>0) or SHIP_TONNAGE IS NULL) ,
    Ship_CAUSE     VARCHAR2(100) NULL CHECK (SHIP_CAUSE IN ('Fire', 'Collision','Unknown',' Deliberate', 'Explosion',' Attack', 'Other')),
    Ship_DATESUNK  DATE NULL,
    Ship_CONDITION VARCHAR2(50) NULL CHECK (SHIP_CONDITION IN ('Excellent', 'Moderate','Poor', 'Very Poor')),
    CONSTRAINT SHIPWRECK_PK PRIMARY KEY (SITE_ID)
  );