2017-04-23 69 views
0

我從java創建動態表。我想要的是,我想創建一個觸發器添加每個新表,將只使用序列填充主鍵(serial_no),這是在每個表中常見的。如何實現這?在過程中動態添加的表上創建觸發器

編輯: 我曾嘗試這個代碼,但我'越來越

create or replace procedure "TRIGGER_CALL" (trigger_name IN VARCHAR2, table_name IN VARCHAR2, sno IN NUMBER) as begin CREATE SEQUENCE abc MINVALUE 1 MAXVALUE 10000 INCREMENT BY 1 START WITH 141 CACHE 20 NOORDER NOCYCLE; CREATE OR REPLACE TRIGGER trigger_name before insert on table_name for each row begin select s_no.nextval into :new.sno from dual; end; end; 

EDIT2消息 「與編譯錯誤創建程序」: 我的代碼

CREATE OR REPLACE 
PROCEDURE "TRIGGER_CALL" (p_table_name IN VARCHAR2) 
AUTHID CURRENT_USER       
AS 
    l_sql VARCHAR2(4000); 
    l_dummy NUMBER; 
    l_trigger_name VARCHAR2(30); 
    l_seq_name VARCHAR2(30); 
BEGIN 

    --SELECT '1' 
    --INTO l_dummy 
    --FROM all_tables 
    -- WHERE table_name = UPPER(p_table_name); 

    l_trigger_name := p_table_name || '_trg'; 
    l_seq_name := p_table_name || 's_no'; 
EXECUTE IMMEDIATE 'CREATE SEQUENCE l_seq_name start with 1 increment by 1 '; 
    l_sql := 
    'CREATE OR replace TRIGGER ' || l_trigger_name || 
    ' BEFORE INSERT ON ' || p_table_name || 
    ' FOR EACH ROW 
    BEGIN 
     SELECT l_seq_name.NEXTVAL 
     INTO :new.sno 
     FROM dual; 
    END;'; 

    EXECUTE IMMEDIATE l_sql; 
END; 
/
+0

什麼是您的Oracle版本?這在12c中更容易。 –

+0

@WilliamRobertson我有Oracle 10g。有什麼建議麼 ?? –

+0

你必須做很長的路,然後 - 爲你創建的每個表動態地定義一個序列和一個觸發器。 –

回答

1

請檢查下面的代碼:

CREATE SEQUENCE my_sequence; 
/

CREATE OR REPLACE 
PROCEDURE "TRIGGER_CALL" (p_table_name IN VARCHAR2) 
AUTHID CURRENT_USER       
AS 
    l_sql VARCHAR2(4000); 
    l_dummy NUMBER; 
    l_trigger_name VARCHAR2(30); 
BEGIN 
    -- Validate if a p_table_name is a valid object name 
    -- If you have access you can also use DBMS_ASSERT.SQL_OBJECT_NAME procedure 
    SELECT '1' 
    INTO l_dummy 
    FROM all_tables 
    WHERE table_name = UPPER(p_table_name); 

    l_trigger_name := p_table_name || '_trg'; 

    l_sql := 
    'CREATE OR replace TRIGGER ' || l_trigger_name || 
    ' BEFORE INSERT ON ' || p_table_name || 
    ' FOR EACH ROW 
    BEGIN 
     SELECT my_sequence.NEXTVAL 
     INTO :new.sno 
     FROM dual; 
    END;'; 

    EXECUTE IMMEDIATE l_sql; 
END; 
/

CREATE TABLE my_test(sno NUMBER); 
/

BEGIN 
    trigger_call('my_test'); 
END; 
/

重要注意事項:

  1. AUTHID CURRENT_USER的使用消除了「權限不足」問題。僅供參考,請參閱:Execute Immediate within a stored procedure keeps giving insufficient priviliges error

  2. 因爲動態SQL只是簡單地連接輸入參數,所以需要對其進行驗證以防止SQL注入。另見DBMS_ASSERT

  3. 因爲第2點。我使用表名來構建觸發器名稱。

+0

我收到此錯誤消息「oracle pls-00103在遇到以下任一項時遇到符號創建」 –

+0

我無法在沒有看到您的代碼的情況下爲您提供幫助。 – kpater87

+0

我發佈了我的code.Check it! –

相關問題