代码之家  ›  专栏  ›  技术社区  ›  Colin Bowern

Oracle脚本中的错误处理

  •  5
  • Colin Bowern  · 技术社区  · 14 年前

    我已经想了一段时间了,我想是时候寻求帮助了。。我正在构建一个模式配置脚本,我想添加一些脚本输出和错误处理。其思想是,脚本输出窗口将只向我显示关键消息,而没有所有的噪音。

    Create Temporary Error Table
    Begin Transaction
    
    -- begin work block
    Print "Doing some types of work"
    -- do work here
    
    If Error and Active Transactions > 0 Then Rollback
    If Active Transactions = 0 Then Insert Error In Temp Error Table and Start Another Transaction
    -- end work block
    
    -- once all all work complete
    If Active Transactions > 0 Then Commit Transactions
    

    Red Gate's SQL Packager

    2 回复  |  直到 14 年前
        1
  •  2
  •   Adam Musch    14 年前

    在Oracle中,您定义事务边界——完成后提交,并且每条语句都是原子的。

    如果您使用的是SQL*Plus,并且如果出现任何问题,您根本不希望提交任何内容,那么可以在SQL脚本中执行以下操作:

    SET ECHO ON
    SPOOL /some/path/to/logfile.log
    WHENEVER SQLERROR EXIT SQL.CODE ROLLBACK
    
    -- run your code or DML statements
    
    COMMIT;
    EXIT;
    

    COMMIT 或引起它们的语句,如 CREATE, ALTER, DROP, GRANT ,或 REVOKE

        2
  •  0
  •   Rajesh Chamarthi    14 年前

    在我看到的大多数情况下,这样的(重复的)任务是使用脚本自动执行的。

    我们目前使用的一种方法是UNIX脚本,它运行给定目录中的所有.sql文件并生成一个.log文件。在这个过程的最后,我们对日志文件进行grep,看看是否有任何错误。

    您不需要手动打印任何错误,因为sqlplus已经打印出错误,并将其捕获到日志文件中。

    下面是一个非常简单的例子。。。

    .ksh文件

    #!/usr/bin/ksh
    echo "Starting provisioning script.."
    
    sqlplus scott/tiger@oracle102 > file1.log << !
    @file1.sql
    @file1.sql
    !
    
    echo "end of provisioning script"
    

    以及file1.sql的内容(对于本例,它位于同一目录中)

    create table test123(
       id number,
       name varchar2(200)
    );
    

    当我运行这个脚本时,第一个创建成功,第二个失败..日志文件将是。。就像。。

    SQL*Plus: Release 10.2.0.4.0 - Production on Fri Aug 6 20:44:08 2010
    
    Copyright (c) 1982, 2007, Oracle.  All Rights Reserved.
    
    
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    
    SQL>
    Table created.
    
    SQL> create table test123(
                 *
    ERROR at line 1:
    ORA-00955: name is already used by an existing object
    
    
    SQL> Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    

    你可以按照这些思路准备剧本。。然后在日志文件中查找任何错误。。一旦执行完成。您可以使用各种sqlplus会话命令来删除所有不需要的注释等。

    我不知道有任何自动工具也能做到这一点。我一直