-
慕仙森
SYS_GUID返回一个GUID-一个全局唯一的ID。一个SYS_GUID是RAW(16)。它不生成递增的数值。如果要创建一个递增的数字键,则需要创建一个序列。CREATE SEQUENCE name_of_sequence START WITH 1
INCREMENT BY 1
CACHE 100;然后,您可以在您的INSERT陈述INSERT INTO name_of_table( primary_key_column, <<other columns>> )
VALUES( name_of_sequence.nextval, <<other values>> );或者,可以定义一个触发器,该触发器使用序列自动填充主键值。CREATE OR REPLACE TRIGGER trigger_name
BEFORE INSERT ON table_name FOR EACH ROWBEGIN
SELECT name_of_sequence.nextval INTO :new.primary_key_column FROM dual;END;如果使用的是Oracle 11.1或更高版本,则可以稍微简化触发器CREATE OR REPLACE TRIGGER trigger_name
BEFORE INSERT ON table_name FOR EACH ROWBEGIN
:new.primary_key_column := name_of_sequence.nextval;END;如果你真的想用SYS_GUIDCREATE TABLE table_name (
primary_key_column raw(16) default sys_guid() primary key,
<<other columns>>)
-
噜噜哒
在甲骨文12c中,你可以这样做,CREATE TABLE MAPS(
MAP_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL,
MAP_NAME VARCHAR(24) NOT NULL,
UNIQUE (MAP_ID, MAP_NAME));在甲骨文(前12C)。-- create tableCREATE TABLE MAPS(
MAP_ID INTEGER NOT NULL ,
MAP_NAME VARCHAR(24) NOT NULL,
UNIQUE (MAP_ID, MAP_NAME));-- create sequenceCREATE SEQUENCE MAPS_SEQ;-- create tigger using the sequenceCREATE OR REPLACE TRIGGER MAPS_TRG
BEFORE INSERT ON MAPS
FOR EACH ROWWHEN (new.MAP_ID IS NULL)BEGIN
SELECT MAPS_SEQ.NEXTVAL INTO :new.MAP_ID FROM dual;END;/
-
汪汪一只猫
这里有三种口味:数字。简单增加数值,例如1,2,3,.吉德。全局Univeral标识符,作为RAW数据类型。GUID(字符串)。和上面一样,但是作为一个字符串,在某些语言中可能更容易处理。x身份列。代用FOO在每个示例中使用您的表名。-- numerical identity, e.g. 1,2,3...create table FOO (
x number primary key);create sequence FOO_seq;create or replace trigger FOO_trg
before insert on FOOfor each rowbegin
select FOO_seq.nextval into :new.x from dual;end;/-- GUID identity, e.g. 7CFF0C304187716EE040488AA1F9749A-- use the commented
out lines if you prefer RAW over VARCHAR2.create table FOO (
x varchar(32) primary key -- string version
-- x raw(32) primary key -- raw version);create or replace trigger FOO_trg
before insert on FOOfor each rowbegin
select cast(sys_guid() as varchar2(32)) into :new.x from dual; -- string version
-- select sys_guid() into :new.x from dual; -- raw versionend;/最新情况:Oracle 12c引入了这两个不依赖触发器的变体:create table mytable(id number default mysequence.nextval);create table mytable(id number generated as identity);第一种方法以传统方式使用序列;第二种方法在内部管理值。