oracle Oracle数据库中的自增主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2588903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 20:22:33  来源:igfitidea点击:

Autoincrement Primary key in Oracle database

sqloracleauto-increment

提问by GigaPr

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

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

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

How can this be done?

如何才能做到这一点?

回答by Matthew Watson

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.

正如 Orbman 所说,执行此操作的标准方法是使用序列。大多数人还做的是将其与插入触发器结合使用。因此,当插入没有 ID 的行时,触发器会触发以从序列中为您填写 ID。

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.

这是在 Oracle 中使用触发器有意义的少数情况之一。

回答by Adam Hawkes

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.

如果您真的不关心主键包含什么,您可以对主键列使用 RAW 类型,该列以二进制形式保存系统生成的 guid。

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