2016-02-18 24 views
0

我在MySQL中創建一個數據庫〜10桌,每個開始列使用相同的自動遞增觸發在oracle中的許多表

SN INT NOT NULL AUTO_INCREMENT 

SN並不意味着什麼,只是一次區分可能重複/相似的名稱/標題等

我現在將它移動到Oracle,並且發現this post here on stackoverflow使觸發器自動遞增SN字段。基本上,

CREATE SEQUENCE user_seq; 

CREATE OR REPLACE TRIGGER user_inc 
BEFORE INSERT ON users 
FOR EACH ROW 

BEGIN 
    SELECT user_seq.NEXTVAL 
    INTO :new.SN 
    FROM dual; 
END; 
/

現在,我該如何重寫該觸發器一次適用於所有其他表?因爲否則我不得不把它改寫了多個表,只是改變了觸發名稱和序列的名字......我想象類似:

BEFORE INSERT ON users OR other_table OR another_one 

我還發現this post here,但一個答案沒有幫助,因爲我認爲很多桌子有相同的SN場是合理的,或者我誤解了這一點。

而且,並非甲骨文12C所以沒有標識列

在此先感謝

我只打算在我提到的第一篇文章發表評論,但我不能沒有更多的聲望點數評論:/

回答

2

在Oracle中創建引用多個表的觸發器是不可能的, 您可以做的是使用PL/SQL語句生成觸發器。

下面是你如何能做到這一點

drop table tab_a; 
drop table tab_b; 
drop table tab_c; 

drop sequence seq_tab_a_id; 
drop sequence seq_tab_b_id; 
drop sequence seq_tab_c_id; 

--create test tables 
create table tab_a (SN number, otherfield varchar2(30), date_field date); 
create table tab_b (SN number, otherfield varchar2(30), date_field date); 
create table tab_c (SN number, otherfield varchar2(30), date_field date); 

-- this pl/sql block creates the sequences and the triggers 
declare 
    my_seq_create_stmt varchar2(2000); 
    my_trigger_create_stmt varchar2(2000); 
begin 

    for i in (select table_name 
       from user_tables 
      -- remember to change this where condition to filter 
      -- the tables that are relevant for you 
      where table_name in ('TAB_A', 'TAB_B', 'TAB_C'))loop <<TableLoop>> 

    my_seq_create_stmt := 'CREATE SEQUENCE '||'SEQ_'||i.table_name||'_ID ' 
         ||CHR(13)||' START WITH 1 INCREMENT BY 1 NOCYCLE '; 

    execute immediate my_seq_create_stmt; 
    my_trigger_create_stmt := 'CREATE OR REPLACE TRIGGER '||'TRG_'||i.Table_name||'_ID_BI '||' BEFORE INSERT ON '||i.table_name||' FOR EACH ROW ' 
        ||CHR(13)||'BEGIN ' 
        ||CHR(13)||' SELECT '||'SEQ_'||i.table_name||'_ID'||'.NEXTVAL ' 
        ||CHR(13)||' INTO :new.SN ' 
        ||CHR(13)||' FROM dual; ' 
        ||CHR(13)||'END; '; 

    execute immediate my_trigger_create_stmt; 
end loop TableLoop; 
end; 
/

-- test the triggers and the sequences 
insert into tab_a (otherfield, date_field) values ('test 1',sysdate); 
insert into tab_a (otherfield, date_field) values ('test 2',sysdate); 

commit; 


Select * from tab_a; 
+0

這很有趣的例子,以前從未使用PL/SQL。我是否需要安裝一些驅動程序或其他東西來使用它?另外我不明白'table_name'和'user_tables'在這個部分:'for i in(select table_name from user_tables' – North

+0

嗨, PL/SQL是ORACLE數據庫的標準部分 USER_TABLES是字典視圖,其中包含DB的元數據 https://docs.oracle.com/cd/B28359_01/server.111/b28310/tables014.htm –

相關問題