admin

创建新表时,在插入之前创建触发器生成ID列值

sql

当在模式中创建表(MYSCHEMA)时,我需要创建一个触发器,该触发器会在插入每个创建的表之前从序列中生成一个ID列。如何实现这一点?

我知道,如何通过触发器和序列来实现ID列的生成,如下所示:

CREATE OR REPLACE TRIGGER TR1
  BEFORE INSERT ON TB1
  FOR EACH ROW
BEGIN
  SELECT SQ1.nextval
    INTO :new.primary_key_column
    FROM dual;
END;

但是我不知道,如何在我的架构中使用AFTER CREATE ON SCHEMA触发器CREATE TABLEBEFORE INSERT…之后创建触发器?

我写了这段代码:

CREATE OR REPLACE TRIGGER /*APPROOT*/after_create_table_trigger
AFTER CREATE ON APPROOT.SCHEMA
DECLARE 
TABLE_NAME VARCHAR2(100);
BEGIN
IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN
SELECT ORA_DICT_OBJ_NAME INTO TABLE_NAME FROM DUAL;
EXECUTE IMMEDIATE 
('CREATE OR REPLACE TRIGGER id_table_gen
  BEFORE INSERT ON ' || TABLE_NAME ||
  ' FOR EACH ROW
   BEGIN
    SELECT APPROOT.AE_IDSEQ.NEXTVAL
     INTO :new.ID
     FROM dual;
   END;');
END IF;
END;
/

然后,我用一个字段-ID创建了测试表,但是我的触发器不起作用…我认为使用事件属性函数ora_dict_obj_name的原因是错误的。

有人可以给我建议吗?

谢谢你。


阅读 149

收藏
2021-06-07

共1个答案

admin

如果我将架构名称放在DDL中,则可以正常工作。

SQL> connect sys/test as sysdba
Connected.
SQL> CREATE OR REPLACE TRIGGER after_create_table_trigger
  2  AFTER CREATE ON TEST.SCHEMA
  3  DECLARE
  4  TABLE_NAME VARCHAR2(100);
  5  BEGIN
  6  IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN
  7  SELECT ORA_DICT_OBJ_NAME INTO TABLE_NAME FROM DUAL;
  8  EXECUTE IMMEDIATE
  9  ('CREATE OR REPLACE TRIGGER ID_TABLE_GEN
 10    BEFORE INSERT ON TEST.' || TABLE_NAME ||
 11    ' FOR EACH ROW
 12     BEGIN
 13      SELECT TEST.AE_IDSEQ.NEXTVAL
 14       INTO :new.ID
 15       FROM dual;
 16     END;');
 17  END IF;
 18  END;
 19  /

Trigger created.

SQL> connect test/test
Connected.
SQL> create table mytab(id number primary key, a varchar2(1));

Table created.

SQL> insert into mytab (a) values ('a');

1 row created.

SQL> select * From mytab;

        ID A
---------- -
         1 a


SQL> select * from v$version;

BANNER
----------------------------------------------------------------
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
PL/SQL Release 10.2.0.4.0 - Production
CORE    10.2.0.4.0      Production
TNS for Linux: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production

ps不需要做

SELECT ORA_DICT_OBJ_NAME INTO TABLE_NAME FROM DUAL;

只需将其粘贴到命令中即可。

CREATE OR REPLACE TRIGGER ID_TABLE_GEN
  BEFORE INSERT ON APPROOT.' || ORA_DICT_OBJ_NAME ||
2021-06-07