简体   繁体   中英

Make value of a DB column auto increment by 1 in Oracle 11g

I have Oracle DB 11g Enterprise Edition and I want to create a table by reading the sql script from following file:

CREATE SEQUENCE VerHist_SeqNum
   START WITH 1 
   INCREMENT BY 1;


CREATE TABLE VerHist
(
  SequenceNumber NUMBER(10,0)  NOT NULL,
  SQLFileName VARCHAR2(100)  NOT NULL,
  STATUS VARCHAR2(10)  NOT NULL,
  AppliedDate DATE  NOT NULL,
  DateCreated DATE 
   DEFAULT (SYSDATE),
  DateUpdated DATE 
   DEFAULT (SYSDATE),
  CONSTRAINT PK_VerHist PRIMARY KEY( SequenceNumber ),
  CONSTRAINT UC_VerHist_SQLFileNa UNIQUE( SQLFileName )
);


CREATE OR REPLACE TRIGGER VerHist_SeqNum_TRG
   BEFORE INSERT 
   ON VerHist
   FOR EACH ROW
   BEGIN
:NEW.SequenceNumber := VerHist_SeqNum.NEXTVAL;
   END;

Through java code I am reading above sql script and then executing following 3 queries:

  1. Create Sequence
  2. Create Table
  3. Create Trigger which auto increment the 'SequenceNumber' when INSERT query is run

I have created this sql script by converting from my MS SQL Server script, where I only have to run a single query instead of 3 in this case.

My question is, Is it possible to not have Sequence and the Trigger just for the auto-increment purpose and can I simply modify my Create table query to do this, the way it is done in MS SQL using CONSTRAINT.

I want to do this because say if I drop the table and create new one then I would like to have the sequence restart from 1, whereas in current scenario it won't.

For Oracle 11g , you will have to use the approach you have used. There is no auto-increment functionality available, to help you do away with the sequence and the trigger.

As you say, you might want to drop the table, and want the sequence to start at 1, for that, you would need to recreate the sequence, so that it starts at desired value.

Starting Oracle 12c, IDENTITY columns are available, which can help you implement auto-increment feature. For more details, refer to this

No, it is Not possible.

The syntax diagrams for creating a table in Oracle can be found here: http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_7002.htm

Looking into this specification from Oracle, it would be easy to see that the CREATE TABLE statement doesn't allow creating sequences or triggers as part of creating a table (and in fact, each of these tasks - creating a table, creating a sequence, and creating a trigger - are considered separate DDL commands in Oracle); Nor does Oracle allow to define such a constraint for a column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM