Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

Oracle sql | Share generated by default on null as identity

Is it possible to share the same "pool" for ids when using following syntax?

create table TEST (
   ID INTEGER
      generated by default on null as identity ( start with 1 nocycle noorder)  not null
      constraint CKC_ID  check (ID >= 0),
   constraint PK_ID  primary key (ID )
);


create table TEST2 (
   ID INTEGER
      generated by default on null as identity ( start with 1 nocycle noorder)  not null
      constraint CKC_ID2  check (ID >= 0),
   constraint PK_ID2  primary key (ID )
);

When both attribute have the same name? The only possibility I came up was to start both at different values. Like Test on 1000 and test 2 on 2000 but this is not a long term solution. I'm looking to a solution where I can "share" the same "pool" for ids, so that the id's will never overlap.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use DEFAULT ON NULL with a sequence:

CREATE SEQUENCE test_seq;

CREATE TABLE TEST (
   ID INT
      DEFAULT ON NULL TEST_SEQ.NEXTVAL
      NOT NULL
      CONSTRAINT PK_ID PRIMARY KEY
      CONSTRAINT CKC_ID  check (ID >= 0)
);

CREATE TABLE TEST2 (
   ID INT
      DEFAULT ON NULL TEST_SEQ.NEXTVAL
      NOT NULL
      CONSTRAINT PK_ID2 PRIMARY KEY
      CONSTRAINT CKC_ID2  check (ID >= 0)
);

Then if you insert some data:

INSERT INTO test ( id ) VALUES ( NULL );
INSERT INTO test2 ( id ) VALUES ( NULL );
INSERT INTO test2 ( id ) VALUES ( NULL );
INSERT INTO test ( id ) VALUES ( NULL );

Then:

SELECT * FROM test;
| ID |
| -: |
|  1 |
|  4 |
SELECT * FROM test;
| ID |
| -: |
|  2 |
|  3 |

db<>fiddle here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...