I have an oracle database table:
CREATE TABLE "DogInfo" (
"Id" NUMBER NOT NULL ENABLE,
"DogName" VARCHAR2 (50 CHAR) NOT NULL ENABLE,
"DogAge" NUMBER NOT NULL ENABLE,
CONSTRAINT "DogInfo_PK" PRIMARY KEY ("Id") ENABLE
);
CREATE SEQUENCE "DOGINFO_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE;
CREATE OR REPLACE TRIGGER "BI_DogInfo"
BEFORE INSERT ON "DogInfo" FOR EACH ROW
WHEN (NEW."Id" IS NULL OR NEW."Id" = 0) BEGIN
SELECT "USERINFO_SEQ".nextval INTO :NEW."Id" FROM dual;
END;
ALTER TRIGGER "BI_DogInfo" ENABLE;
If I insert 20 records into the table with database tool, and then use my C# web application to insert records, the dog id will start with 1, rather than 21.
Anyone can help me fix this bug?
Thanks.
Sequence is not an “auto increment id”.
Sequence is just a sequential unique number generator. It can work as your Id column value provider but it is up tu You to keep proper values in the column.
I assume that You add your 20 rows like this:
Your sequence has no way of knowing what is the next number you “expect” it to have (unless of course you (re)create it with desired initial value).
Instead You should always use values from your sequence like this:
This way you’ll keep sequence in sync with table id values.
EDIT :
You can imitate that behaviour by using trigger and sequence as described in this answer.
Also IDENTITY column is now available on Oracle 12c