Autoincrement Primary key in Oracle database

心不动则不痛 提交于 2019-12-06 02:07:54

问题


I would like to achieve an identity or auto-incrementing value in a column ala SQL Server:

CREATE TABLE RollingStock
( 
      Id NUMBER IDENTITY(1,1),
      Name Varchar2(80) NOT NULL      
);

How can this be done?


回答1:


As Orbman says, the standard way to do it is with a sequence. What most people also do is couple this with an insert trigger. So, when a row is inserted without an ID, the trigger fires to fill out the ID for you from the sequence.

CREATE SEQUENCE SEQ_ROLLINGSTOCK_ID START WITH 1 INCREMENT BY 1 NOCYCLE;

CREATE OR REPLACE TRIGGER BI_ROLLINGSTOCK
BEFORE INSERT ON ROLLINGSTOCK
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
 WHEN (NEW.ID IS NULL)
BEGIN
  select SEQ_ROLLINGSTOCK_ID.NEXTVAL
   INTO :NEW.ID from dual;
END;

This is one of the few cases where it makes sense to use a trigger in Oracle.




回答2:


If you really don't care what the primary key holds, you can use a RAW type for the primary key column which holds a system-generated guid in binary form.

CREATE TABLE RollingStock 
(  
  ID RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, 
  NAME VARCHAR2(80 CHAR) NOT NULL       
); 


来源:https://stackoverflow.com/questions/2588903/autoincrement-primary-key-in-oracle-database

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