【问题标题】:Unique value generation for primary key for multiple tables为多个表的主键生成唯一值
【发布时间】:2016-12-03 04:52:04
【问题描述】:

我确实有 3 张桌子。我想为下表中的每个生成 ID,并且在每个表中应该是唯一的。 表 1 ID - 主要 ID 1 -> 2 -> 3 表 2 ID - 主要 ID 4 -> 5 表 3 ID - 主要 ID 6 -> 7 -> 8 每当对上述表格进行新条目时,它应该在表格中生成唯一值 下次我想在表 1 中插入 2 条记录时,应该是 表 1 ID - 主要 ID 9 -> 10.

我们是否可以在 Oracle 中创建一个触发器来完成此操作

【问题讨论】:

    标签: oracle oracle11g


    【解决方案1】:

    在每个表上使用触发器并创建Sequence

    CREATE SEQUENCE seq
     START WITH     1
     INCREMENT BY   1
     NOCACHE
     NOCYCLE;
    

    然后在插入触发器上执行以下操作:

       select seq.nextval 
         into :new.id
         from dual;
    

    这是以前问过的。看here

    CREATE OR REPLACE TRIGGER my_trigger
      BEFORE INSERT 
      ON qname
      FOR EACH ROW
      -- Optionally restrict this trigger to fire only when really needed
      WHEN (new.qname_id is null)
    DECLARE
      v_id qname.qname_id%TYPE;
    BEGIN
      -- Select a new value from the sequence into a local variable. As David
      -- commented, this step is optional. You can directly select into :new.qname_id
      SELECT qname_id_seq.nextval INTO v_id FROM DUAL;
    
      -- :new references the record that you are about to insert into qname. Hence,
      -- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
      -- obtained from your sequence, before inserting
      :new.qname_id := v_id;
    END my_trigger;
    

    【讨论】:

    • 你能帮我为表格创建触发器吗?以及此序列如何链接到触发器
    • @user2677675 我发布了一个从 SO 中提取的示例。
    • 在实际场景中,我确实有超过 20 多个表。因此我需要创建 20 多个触发器。有什么方法可以在 20+ 表上创建一个触发器来生成序列号
    • @user2677675 不,您必须创建 20 多个触发器。每张桌子上一个。它们几乎相同,您可以动态执行此操作。
    猜你喜欢
    • 2012-01-27
    • 2020-09-09
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2017-04-22
    相关资源
    最近更新 更多