【问题标题】:Oracle procedure/function to create a trigger in table在表中创建触发器的 Oracle 过程/函数
【发布时间】:2018-02-23 21:48:46
【问题描述】:

我正在尝试创建一个给定表名的过程,它将创建一个序列和自动递增触发器,所有这些都使用基于表名的变量。

代码:

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 符号),但我确定我犯了其他错误。

谁能帮我弄清楚这个逻辑?

【问题讨论】:

  • 您不能在 pl/sql 块中执行 DDL 语句。您要么必须使用立即执行,要么只需编写一个脚本并通过 sqlplus 运行

标签: sql oracle stored-procedures oracle11g


【解决方案1】:

您不能将 DDL 语句(如 dropcreatealter)直接放在 PL/SQL 块中。如果你想在 PL/SQL 中做 DDL,你可以做一个execute immediate:

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

【讨论】:

    猜你喜欢
    • 2013-12-24
    • 2018-02-07
    • 1970-01-01
    • 2019-08-08
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多