我想在第6列中插入第4和第5列的日期差异,但它给出了错误,指出列不允许。
insert into leave25 vALUES (4, 4, 'SICK', TO_DATE('22-AUG-14','DD-MON-YY'), TO_DATE('22-SEP-14','DD-MON-YY'), startdate-enddate)\\
答案 0 :(得分:3)
始终在INSERT
语句中明确指定列名称。这样更安全。
如果您想避免再次写日期,可以从子查询中选择值。
INSERT INTO leave25
(col1,
col2,
col3,
startdate,
enddate,
days)
SELECT t.*,
startdate - enddate
FROM (SELECT 4,
4,
'SICK',
to_date('22-AUG-14', 'DD-MON-YY') as startdate,
to_date('22-SEP-14', 'DD-MON-YY') as enddate
FROM dual) t;
此外,我同意Aleksej,最好将此差异存储为 virtual column 而不是列本身。
答案 1 :(得分:2)
你不能这样做,你需要明确地使用你想要插入的值:
INSERT INTO leave25
VALUES (
4,
4,
'SICK',
TO_DATE('22-AUG-14', 'DD-MON-YY'),
TO_DATE('22-SEP-14', 'DD-MON-YY'),
TO_DATE('22-SEP-14', 'DD-MON-YY') - TO_DATE('22-AUG-14', 'DD-MON-YY')
此外,如果此列始终包含该差异,您确定需要存储此冗余信息吗?
另一种方法可以是使用触发器填充该列而不显式赋值,但这取决于您的环境和您的需求。
答案 2 :(得分:1)
使用虚拟列:
CREATE TABLE Leave25(
EMPLOYEEID INTEGER
CONSTRAINT LEAVE25__EMPID__FK REFERENCES Employee24,
LEAVEID INTEGER
CONSTRAINT LEAVE25__LEAVEID__PK PRIMARY KEY,
LEAVETYPE VARCHAR2(20)
CONSTRAINT LEAVE25__LEAVETYPE__NN NOT NULL
CONSTRAINT LEAVE25__LEAVETYPE__CHK CHECK (
LEAVETYPE IN 'EARNED', 'SICK'
),
STARTDATE DATE
CONSTRAINT LEAVE25__STARTDATE__NN NOT NULL,
ENDDATE DATE
CONSTRAINT LEAVE25__ENDDATE__NN NOT NULL,
DURATION NUMBER
GENERATED ALWAYS AS ( ENDDATE - STARTDATE ) VIRTUAL
);
创建一个序列来管理主键:
CREATE SEQUENCE LEAVE25__LEAVEID__SEQ;
然后你可以这样做:
INSERT INTO leave25 (
EMPLOYEEID, LEAVEID, LEAVETYPE, STARTDATE, ENDDATE
) VALUES (
4, LEAVE25__LEAVEID__SEQ.NEXTVAL, 'SICK', DATE '2014-08-22', DATE '2014-09-22'
)