1

我有一个小 SQL 脚本,我正在使用 Oracle 的 SQL*Plus 来模拟表上的创建或替换:

BEGIN
    EXECUTE IMMEDIATE 'DROP TABLE symbols';
EXCEPTION
    WHEN OTHERS THEN
        IF SQLCODE != -942 THEN
    END IF;
END;
/
CREATE TABLE symbols ( 
            blah blah,
            blah blah,
        );
EXIT;

SQL*Plus 命令行是:

sqlplus aegsys15_owner/pass#234@MARVINUAT03 @createSymbolsTable.sql << EOF
> EOF

如果我在 END 之后省略了正斜杠 (/),它似乎只处理第一个 BEGIN/END 块,并忽略下面的 CREATE TABLE 部分。此外,它根本不会打印任何帮助 - 只是连接/断开连接:

SQL*Plus: Release 11.2.0.1.0 Production on Tue Sep 13 15:49:34 2011

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

 78  Disconnected from Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

但是,如果我确实有正斜杠,它会给我一个错误:

    END IF;
    *
ERROR at line 6:
ORA-06550: line 6, column 5:
PLS-00103: Encountered the symbol "END" when expecting one of the following:
( begin case declare exit for goto if loop mod null pragma
raise return select update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
continue close current delete fetch lock insert open rollback
savepoint set sql execute commit forall merge pipe purge

CREATE TABLE symbols (
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

首先,将 BEGIN/END 异常块放在顶部和 CREATE TABLE 块放在同一个 .sql 文件中的最佳方式是什么?

其次,有什么方法可以从 SQL*Plus 中获得一些有用的输出?我们运行的每个 .sql 文件可能有多个 CREATE 语句(表、索引、同义词等)。我们理想的输出是这样的:

TABLE foo: Pass
SYNONYM bar: Fail
INDEX foo_1: Pass

不确定是否可以使用 SQL 或 PL/SQL 实现类似的目标——如果你们认为这是一个更好的解决方案,很高兴围绕这个编写 Bash 或 Python 包装脚本。

干杯,维克多

4

2 回答 2

2

你忘了把你的if语句..

BEGIN     
     EXECUTE IMMEDIATE 'DROP TABLE symbols'; 
EXCEPTION     
  WHEN OTHERS THEN         
   IF SQLCODE != -942 THEN     
 --here you have to write something for this exception
 -- if you don't have any activity to do then you can use NULL (atleast)
 -- you can't put this if statement body empty in oracle
 NULL;
END IF; 
END; 
/ 

如果你declare也在第一行使用更好,在开始之前

于 2011-09-13T06:10:05.763 回答
-1

对于 slqplus 中的输出,请使用 prompt 命令。对于来自 pl/sql 的输出(即在开始/结束块内),请使用 dbms_output.put_line() 函数。

prompt Creating foo table
begin
  create table foo...;
  dbms_output.put_line('success');
exception
  when others then
    dbms_output.put_line('fail');
end;
/
于 2011-09-13T07:44:01.080 回答