1

我有一个关于 Oracle 数据库 SQL 的问题。

我的员工每个人都有一个项目,项目的结束日期取决于根据 PTerm 给予他们的月份数。我这样做对吗?

CREATE TABLE PROJECT ( P_ID VARCHAR ( 20 ) NOT NULL,
                   PNAME VARCHAR ( 100 ) NOT NULL,
                   PTERM VARCHAR ( 20 ),
                   PSTARTDATE DATE,
                   PENDDATE DATE,
                   CONSTRAINT PROJECT_PKEY PRIMARY KEY ( P_ID ),
                   CONSTRAINT PROJECT_PTERM CHECK
                       ( PTERM IN ('1 MONTH', '2 MONTH', '3 MONTH') ),
                   CONSTRAINT PROJECT_ENDDATE CHECK
                       ( PENDDATE = (PSTARTDATE + PTERM) ) );
4

2 回答 2

0

好的,我刚刚看到你提到了 Oracle,所以我会试试这个

 CREATE TABLE PROJECT (

P_ID          VARCHAR(20) not null,
PName         VARCHAR(100) not null,
PTerm         VARCHAR(20),
PStartDate    DATE,
PEndDate      DATE,
constraint project_Pkey primary key (P_ID),
constraint project_pterm CHECK ( PTERM IN 
                        ('1 MONTH', '2 MONTH', '3 MONTH')),
constraint project_enddate CHECK(PEndDate = (add_months(PStartDate, to_number(substr(pTerm, 1, 1)))))

);

我相信如果你有一个字段来指示 number(10) 中的月数而不是 varchar 会更好,这样你就可以使用这个字段而不是在 varchar 字段中进行所有这些 substr 和 to_number 转换

于 2013-10-29T15:48:17.300 回答
0

如果这是甲骨文,那么我会走这条路

CREATE TABLE PROJECT ( P_ID VARCHAR ( 20 ) NOT NULL,
                   PNAME VARCHAR ( 100 ) NOT NULL,
                   PTERM VARCHAR ( 20 ),
                   PSTARTDATE DATE,
                   PENDDATE DATE,
                   CONSTRAINT PROJECT_PKEY PRIMARY KEY ( P_ID ),
                   CONSTRAINT PROJECT_PTERM CHECK
                       ( PTERM IN ('1', '2', '3') ),
                   CONSTRAINT PROJECT_ENDDATE CHECK
                       ( PENDDATE = ADD_MONTHS(PSTARTDATE , PTERM) ) );

如果我尝试以下插入,它们将失败,因为它严格地在开始日期添加几个月并期望与结束相同。

INSERT INTO
      PROJECT
VALUES
      ( 1,
        'asb',
        2,
        SYSDATE,
        SYSDATE
        + 60 );
--ORA-02290: check constraint (PROJECT_ENDDATE) violated

INSERT INTO
      PROJECT
VALUES
      ( 1,
        'asb',
        2,
        SYSDATE,
        SYSDATE
        + 62 );
--ORA-02290: check constraint (PROJECT_ENDDATE) violated

INSERT INTO
      PROJECT
VALUES
      ( 1,
        'asb',
        2,
        SYSDATE,
        SYSDATE
        + 61 );  
-- 1 row inserted
于 2013-10-29T15:51:42.800 回答