Oracle过程/函数在表中创建触发器

时间:2017-09-14 19:42:28

标签: sql oracle stored-procedures oracle11g

我试图创建一个给出表名的过程,它会创建一个序列并自动递增触发器,所有这些都使用基于表名的变量

代码:

CREATE OR REPLACE procedure CREATE_SEQUENTIAL_TR(table_name VARCHAR)
is -- Tried using declare but it wouldn't accept
    coluna_cod varchar(100 char);
begin
    --Finding the cod column name for this table first
    --They start with "PK_CD"
    select 
        COLUMN_NAME 
    into
        coluna_cod
    from 
        ALL_TAB_COLUMNS 
    where 
        TABLE_NAME=table_name 
        and COLUMN_NAME like "PK_CD%";
    --Creating the sequence obj
    drop sequence "cod" || table_name;
    create sequence "cod" || table_name;
    --Now creating the trigger
    create or replace trigger "cod" || table_name || "tr"           
    before 
        UPDATE or INSERT on table_name
    for each row
    declare
        cod number := coluna_cod;
        tr_name varchar(100 char) := "cod" || table_name
    begin
        if UPDATING then
            if :new.cod != :old.cod then
                :new.cod := :old.cod;
            end if;
        else -- inserting
            :new.cod := tr_name.nextval();
        end if; 
    end;
end;

这种复杂性最终完全超出了我的知识范围。

目前它在drop sequence "cod" || table_name上发出错误(找到了意外的DROP符号),但我确定我发现了其他错误。

有人可以帮助我理解这个逻辑吗?

1 个答案:

答案 0 :(得分:2)

您不能将DDL语句(如dropcreatealter)直接放在PL / SQL块中。如果要在PL / SQL中执行DDL,可以执行execute immediate

declare
begin
  drop sequence X; -- error
  execute immediate 'drop sequence X'; -- works fine 
end;
/