oracel创建自定义主键id按时间加自增长为字符串方式触发器生成

编写orale的过程函数

select (select to_char(sysdate,'yyyyMMddHH24miss') from dual)||lpad( SEQ_ID.nextval, 8, 0 ) 
from dual

创建函数生成方式:

--创建函数
CREATE 
	OR REPLACE FUNCTION get_id RETURN VARCHAR2 IS BEGIN
	RETURN to_char ( sysdate, 'yyyyMMddHH24mi' ) || lpad( SEQ_ID.nextval, 8, 0 );
END;

--创建函数 i_tablename是表名,i_columnname 主键字段名
CREATE 
	OR REPLACE FUNCTION get_recordid(i_tablename in varchar2, i_columnname in varchar2) RETURN VARCHAR2 IS BEGIN
	RETURN to_char ( sysdate, 'yyyyMMddHH24mi' ) || lpad( SEQ_ID.nextval, 8, 0 );
END;

测试调用:

select get_id();
select get_recordid('QB_QKYT_XTGL_DLRZ', 'ID');

 

编写触发器:

-- TRG_QB_QKYT_XTGL_DLRZ自定义的触发器名称 QB_QKYT_XTGL_DLRZ为表名
-- 表示有新数据插入的时候通过if判断主键是否为空 :new.ID是表的主键
-- :new.ID为空的 就让他等于我们上面写的函数来获取id

CREATE OR REPLACE TRIGGER "USER_QKYT_GA"."TRG_QB_QKYT_XTGL_YWYCRZ" BEFORE INSERT ON "USER_QKYT_GA"."QB_QKYT_XTGL_YWYCRZ" REFERENCING OLD AS "OLD" NEW AS "NEW" FOR EACH ROW
  declare
 begin
   if :new.ID is null then
  		:new.ID :=get_id();
   end if;end;
   
CREATE OR REPLACE TRIGGER "USER_QKYT_GA"."TRG_QB_QKYT_XTGL_YWYCRZ"
BEFORE INSERT OR UPDATE OF ID
ON "USER_QKYT_GA"."QB_QKYT_XTGL_YWYCRZ"
FOR EACH ROW
BEGIN
IF INSERTING THEN 
SELECT get_id() INTO :NEW.ID FROM DUAL;
ELSE
RAISE_APPLICATION_ERROR(-20020, '不允许更新ID值!');
END IF;
END;

 

你可能感兴趣的:(oracel创建自定义主键id按时间加自增长为字符串方式触发器生成)