本周,我们公司就如何编写SQL脚本进行了一些讨论。
背景:
我们的数据库是Oracle 10g(即将升级到11)。我们的DBA团队使用SQLPlus将脚本部署到生产环境中。
现在,我们最近有一个部署失败了,因为它同时使用了分号和正斜杠(/)。分号位于每条语句的末尾,斜杠位于语句之间。
alter table foo.bar drop constraint bar1;
/
alter table foo.can drop constraint can1;
/
稍后在脚本中添加了一些触发器,创建了一些视图以及一些存储过程。两者兼备的;并且/会导致每条语句运行两次,从而导致错误(特别是在插入上,插入必须是唯一的)。
在SQL Developer中这不会发生,在TOAD中这也不会发生。如果您运行某些命令,没有/它们将无法工作。
在PL/SQL中,如果你有一个子程序(DECLARE, BEGIN, END),分号将被认为是子程序的一部分,所以你必须使用斜杠。
所以我的问题是:如果你的数据库是Oracle,写SQL脚本的正确方法是什么?既然你知道你的数据库是Oracle,你应该总是使用/?
我知道这是一个老帖子,但我只是偶然发现了它,我觉得这还没有完全解释清楚。
在SQL*Plus中,a /和a;因为他们的工作方式不同。
的;结束SQL语句,而/则执行当前“缓冲区”中的任何内容。所以当你用a;a / the语句实际上执行了两次。
你可以很容易地看到,在运行语句后使用/:
SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options
SQL> drop table foo;
Table dropped.
SQL> /
drop table foo
*
ERROR at line 1:
ORA-00942: table or view does not exist
在这种情况下,人们实际上注意到了错误。
但是假设有这样一个SQL脚本:
drop table foo;
/
这是在SQL*Plus中运行的,这将非常令人困惑:
SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options
SQL> @drop
Table dropped.
drop table foo
*
ERROR at line 1:
ORA-00942: table or view does not exist
/主要是为了运行嵌入了;像创建过程,创建功能,创建包语句和任何开始…块结束。
我想澄清一些更多的用法;和/
在SQLPLUS:
; means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
<newline> after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;), it means, store the statement to the buffer but do not run it.
/ after entering a statement into the buffer (with a blank <newline>) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
RUN or R is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
/ during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
注意:因为;用于PL/SQL结束语句;不能被SQLPLUS用来表示“终止当前语句,执行它并将其存储到SQLPLUS缓冲区”,因为我们希望整个PL/SQL块完全在缓冲区中,然后执行它。PL/SQL块必须以以下方式结束:
END;
/