编写Oracle存储过程

时间:2012-04-20 17:10:10

标签: oracle oracle10g

我没有用oracle写过很多存储过程。我读了一些tutotorials(例如:http://plsql-tutorial.com/plsql-procedures.htm)并尝试按照我所看到的模型建立sp,但我仍然遇到错误。这是一个小样本程序和错误:

create or replace
PROCEDURE TEST_SP()
  BEGIN

insert into tablespace.tablename
select * from testtable;

END TEST_SP;

PLS-00103: Encountered the symbol ")" when expecting one of the following:

   <an identifier> <a double-quoted delimited-identifier>

我得到的印象是我错过了声明部分,但我不明白我应该宣布什么: - /

任何帮助都将不胜感激。


跟随贾斯汀的第一反应建议,现在得到不同的错误:

create or replace
PROCEDURE TEST_SP
 AS
  BEGIN

insert into tablespace.tablename (col1, col2)
select (col1, col2) from testtable;

END TEST_SP;

PLS-00103: Encountered the symbol "AS" when expecting one of the following: 
. , @ in <an identifier> <a double-quoted delimited-identifier> partition subpartition

1 个答案:

答案 0 :(得分:4)

听起来你像是在追求这样的事情。如果您没有声明任何参数,则不希望在过程名称后面加上括号。即使您不打算声明任何局部变量,也需要在AS之前使用关键字IS(或BEGIN)。

create or replace PROCEDURE TEST_SP
AS
BEGIN
  insert into tablespace.tablename
    select * from testtable;
END TEST_SP;

然而,一般来说,编写这样的代码省略列列表是一个坏主意。这假设两个表具有完全相同的列中完全相同的列,因此如果有人决定将其他列添加到其中一个表中,则代码将中断。它还可能会导致您无意中从错误的列复制数据。写一些像

这样的东西通常更健壮
create or replace PROCEDURE TEST_SP
AS
BEGIN
  insert into tablespace.tablename( <<list of columns>> )
    select <<list of columns>>
      from testtable;
END TEST_SP;

作为一个例子

SQL> create table foo( col1 number );

Table created.

SQL> create table foo_cpy( col1 number );

Table created.

SQL> ed
Wrote file afiedt.buf

  1  create or replace procedure test_sp
  2  as
  3  begin
  4    insert into foo( col1 )
  5      select col1
  6        from foo_cpy;
  7* end test_sp;
SQL> /

Procedure created.
相关问题