我对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) ) );
答案 0 :(得分: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)))))
);
我相信如果你有一个字段表示数字(10)而不是varchar,那么你可以使用这个字段而不是在varchar字段中进行所有这些substr和to_number转换
答案 1 :(得分: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', '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