SQLPlus AUTO_INCREMENT Error

大兔子大兔子 提交于 2019-12-07 04:15:40

问题


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?


回答1:


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



回答2:


Oracle has no auto_increment, you need to use sequences.




回答3:


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

CREATE TABLE employee 
(
    id NUMBER GENERATED by default on null as IDENTITY
    ....
)


来源:https://stackoverflow.com/questions/7949343/sqlplus-auto-increment-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!