Get the App
SLTechnology News&Howtos  ›  Database  › 

[oracle11g self-increasing primary key]

Shulou Source: shulou.com Published: 2022-06-01 15:27:42 09月23日 Update

The self-increasing primary key of oracle needs to be implemented by sequence and trigger.

Let's first create a table: the primary key is int to achieve self-increment.

CreatetableTEST

(

ID intPRIMARYKEY

Test1 varchar2 (20)

Test2 varchar2 (20)

Test3 varchar2 (20)

)

Create a sequence:

Create sequence SEQ_TEST

Minvalue 1-minimum

Maxvalue 9999999999999999999999999999999-maximum

Start with 1-start with 1

Increment by 1-add 1 at a time

Nocycle-- accumulate all the time, not cycle

Nocache

Create a trigger to increment the primary key when the data is inserted:

CREATE OR REPLACE TRIGGER tg_test

/ / test table name, id primary key name, seq_test.nextval sequence

BEFORE INSERT ON test

FOR EACH ROW WHEN (new.id is null)

Begin

Select seq_test.nextval into:new.id from dual

End

You can see that when the insert data primary key is empty, the sequence will be used to generate the self-increasing primary key.

/ /-trigger style

CREATE OR REPLACE TRIGGER TRI_SCORE

BEFORE INSERT OR UPDATE ON XUANKE

FOR EACH ROW

BEGIN

/ / if score is empty, make score=0

IF: new.SCORE IS NULL THEN: new.SCORE:= 0

END IF

END

Tags: Sequence trigger data maximum minimum maximum style build one Loop Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft Redmi Shulou Tech Info Apple