Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger to insert sysdate after an insert in Oracle

I tried using the following but apparently it's invalid 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

like image 410
echoblaze Avatar asked Nov 22 '10 17:11

echoblaze


People also ask

How do you create a trigger after insert?

First, we will specify the name of the trigger that we want to create. It should be unique within the schema. Second, we will specify the trigger action time, which should be AFTER INSERT clause to invoke the trigger. Third, we will specify the name of a table to which the trigger is associated.

What is Cascade trigger in Oracle?

The database server allows triggers other than Select triggers to cascade, meaning that the trigger actions of one trigger can activate another trigger. (For further information on the restriction against cascading Select triggers, see Circumstances When a Select Trigger Is Activated.)


1 Answers

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

CREATED_TIMESTAMP  TIMESTAMP  DEFAULT SYSDATE  NOT NULL,
like image 78
DwB Avatar answered Sep 22 '22 00:09

DwB