Oracle数据库中的自动增量主键

Oracle数据库中的自动增量主键

问题描述:

我想在SQL Server列中实现标识或自动递增值:

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      
);

这怎么办?

正如Orbman所说,实现此目标的标准方法是使用序列.大多数人也将其与插入触发器结合在一起.因此,当插入没有ID的行时,触发器将触发以从序列中为您填写ID.

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;

这是在Oracle中使用触发器的少数情况之一.

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