SQL 在 Oracle 中插入后触发插入 sysdate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4248243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 08:22:24  来源:igfitidea点击:

Trigger to insert sysdate after an insert in Oracle

sqloracletriggers

提问by echoblaze

I tried using the following but apparently it's invalid SQL:

我尝试使用以下内容,但显然它是无效的 SQL:

CREATE OR REPLACE TRIGGER QUESTION_DATE BEFORE INSERT ON QUESTION 
FOR EACH ROW
BEGIN
INSERT INTO QUESTION(CREATED_TIMESTAMP) 
VALUES (SYSDATE);
END;

The Question table looks like this so far:

到目前为止,问题表看起来像这样:

CREATE TABLE QUESTION
(   
    QUESTION_ID             INTEGER not null,
    LATEST_QUESTION         INTEGER not null,
    CREATED_USER_ID         INTEGER not null,
    CREATED_TIMESTAMP       TIMESTAMP not null,     
    CONSTRAINT PK_QUESTION  PRIMARY KEY (QUESTION_ID)
);

CREATE SEQUENCE QUESTION_ID_SEQ INCREMENT BY 1 START WITH 1 NOCYCLE NOCACHE NOORDER;

CREATE TRIGGER QUESTION_INSERT BEFORE INSERT ON QUESTION 
FOR EACH ROW
BEGIN
SELECT QUESTION_ID_SEQ.nextval
INTO :new.QUESTION_ID
FROM dual;
END;

I'm using Toad for Oracle V9.0.1.8 if that's relevant

如果相关,我将使用 Toad for Oracle V9.0.1.8

回答by DwB

Dont use a trigger to set a default value in Oracle. Instead, use "DEFAULT" on the column. Here is an exmple column

不要使用触发器在 Oracle 中设置默认值。相反,在列上使用“DEFAULT”。这是一个示例列

CREATED_TIMESTAMP  TIMESTAMP  DEFAULT SYSDATE  NOT NULL,

回答by Tony Andrews

I think you probably want this:

我想你可能想要这个:

CREATE OR REPLACE TRIGGER QUESTION_DATE BEFORE INSERT ON QUESTION 
FOR EACH ROW
BEGIN
 :NEW.CREATED_TIMESTAMP := SYSDATE;
END;

Your trigger tries to insert another row into QUESTION, which would fire the trigger and...

您的触发器尝试将另一行插入到 QUESTION 中,这会触发触发器并...

回答by Stephanie Page

:new.created_timestamp := sysdate

:new.created_timestamp := 系统日期

Instead of insert.

而不是插入。

The insert is already occurring, no need to do it again.

插入已经发生,无需再次执行。

You could also make sysdate the default for the column, but that would allow for the value to be overridden in the insert statement.

您还可以将 sysdate 设为该列的默认值,但这将允许在插入语句中覆盖该值。