Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...