Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLPlus AUTO_INCREMENT Error

When I try and run the following command in SQLPlus:

CREATE TABLE Hotel
(hotelNo NUMBER(4) NOT NULL AUTO_INCREMENT,
hotelName VARCHAR(20) NOT NULL,
city VARCHAR(50) NOT NULL,
CONSTRAINT hotelNo_pk PRIMARY KEY (hotelNo));

I get the following error:

(hotelNo NUMBER(4) NOT NULL AUTO_INCREMENT,
                        *
ERROR at line 2:
ORA-00907: missing right parenthesis

What am I doing wrong?

like image 492
Michael Gruber Avatar asked Oct 31 '11 02:10

Michael Gruber


3 Answers

Many will gripe about this not being a standard feature in Oracle, but when it’s as easy as two more commands after your CREATE TABLE command I can’t see any good reason to use fancy SQL on every insert. First let’s create a simple table to play with.

SQL> CREATE TABLE test
(id NUMBER PRIMARY KEY,
name VARCHAR2(30));
Table created.

Now we’ll assume we want ID to be an auto increment field. First we need a sequence to grab values from.

SQL> CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
Sequence created.

Now we can use that sequence in a BEFORE INSERT trigger on the table.

CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON test
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;
/


SQL> INSERT INTO test (name) VALUES ('Jon');
1 row created.

SQL> INSERT INTO test (name) VALUES (’Bork’);
1 row created.

SQL> INSERT INTO test (name) VALUES (’Matt’);
1 row created.

SQL> SELECT * FROM test;

ID NAME
———- ——————————
1 Jon
2 Bork
3 Matt
like image 164
Dennis Avatar answered Oct 16 '22 10:10

Dennis


Oracle has no auto_increment, you need to use sequences.

like image 2
steve Avatar answered Oct 16 '22 09:10

steve


Or - starting with Oracle 12.1 - you can simply have:

CREATE TABLE employee 
(
    id NUMBER GENERATED by default on null as IDENTITY
    ....
)
like image 1
Tony Abou Zaidan Avatar answered Oct 16 '22 09:10

Tony Abou Zaidan