如何向程序Oracle添加匿名块?

时间:2012-04-26 08:11:48

标签: sql oracle procedures

我如何使用以下代码创建过程,因为我是oracle的新手总是使用sybase / ms sql而且更容易。

DECLARE
    temp     VARCHAR2 (255);
    last_val NUMBER(9, 0);
    CURSOR c1 IS
      SELECT DISTINCT table_name
      FROM   user_tab_cols
      WHERE  column_name = 'id';
BEGIN
    FOR asd IN c1 LOOP
        temp := asd.table_name;

        EXECUTE IMMEDIATE 'select NVL(max("id"),0)+1 from "'||temp||'"' INTO
        last_val;

        BEGIN
            EXECUTE IMMEDIATE 'drop sequence "seq_'|| temp||'"';

            EXECUTE IMMEDIATE 'create SEQUENCE "seq_'|| temp||'" MINVALUE '||
            last_val||
            'MAXVALUE     999999999999999999999999999 INCREMENT BY 1 NOCACHE';

            EXECUTE IMMEDIATE 'select '||temp||'.nextval from dual';

            EXECUTE IMMEDIATE 'ALTER SEQUENCE "seq_'||temp||'" INCREMENT BY 1';
        EXCEPTION
            WHEN OTHERS THEN
              NULL;
        END;
    END LOOP;

    COMMIT;
END; 

1 个答案:

答案 0 :(得分:2)

使用

CREATE OR replace PROCEDURE Proc_name
IS
  temp     VARCHAR2 (255);
  last_val NUMBER(9, 0);
  CURSOR c1 IS
    SELECT DISTINCT table_name
    FROM   user_tab_cols
    WHERE  column_name = 'id';
BEGIN
    FOR asd IN c1 LOOP
        temp := asd.table_name;

        EXECUTE IMMEDIATE 'select NVL(max("id"),0)+1 from "'||temp||'"' INTO
        last_val;

        BEGIN
            EXECUTE IMMEDIATE 'drop sequence "seq_'|| temp||'"';

            EXECUTE IMMEDIATE 'create SEQUENCE "seq_'|| temp||'" MINVALUE '||
            last_val||
            'MAXVALUE     999999999999999999999999999 INCREMENT BY 1 NOCACHE';

            EXECUTE IMMEDIATE 'select '||temp||'.nextval from dual';

            EXECUTE IMMEDIATE 'ALTER SEQUENCE "seq_'||temp||'" INCREMENT BY 1';
        EXCEPTION
            WHEN OTHERS THEN
              NULL;
        END;
    END LOOP;

    COMMIT;
END;

/