Haider Sultan
Haider Sultan

Reputation: 121

Oracle sql adding auto incremented field

I have made a table in oracle which uses auto incremented field thorough sequence.

Here is the sql:

CREATE TABLE Users(
   user_ID   INT          NOT NULL,
   user_name VARCHAR (20)     NOT NULL,
   user_password  VARCHAR (20)              NOT NULL,
   user_role  INT  NOT NULL,

   PRIMARY KEY (user_ID)
);

ALTER TABLE Users 
   ADD FOREIGN KEY (user_role) REFERENCES User_Roles (role_ID);
CREATE SEQUENCE seq_users
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;

Now I need to insert the data into the table through a java program, is there any way, I don't have to use the query like this:

Insert into User_Roles values (seq_user_roles.nextval,'system admin');

User Role Table:
CREATE TABLE User_Roles(
       role_ID   INT              NOT NULL,
       role_name VARCHAR (20)     NOT NULL,


       PRIMARY KEY (role_ID)
);


CREATE SEQUENCE seq_user_roles
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;

I want to insert the data from a java program and can't specify that name of the sequence.

Upvotes: 2

Views: 84

Answers (1)

Tharunkumar Reddy
Tharunkumar Reddy

Reputation: 2813

Crete below trigger after sequence creation. So it will populate date into your column. And no need to mention role_id column in you insert statement script.

CREATE OR REPLACE TRIGGER TRG_User_Roles_BRI
       BEFORE INSERT
       ON User_Roles
       REFERENCING NEW AS NEW OLD AS OLD
       FOR EACH ROW
    BEGIN
       :NEW.role_ID   := seq_user_roles.NEXTVAL;
    END;

Upvotes: 1

Related Questions