为什么这个PL / SQL不起作用?

时间:2016-04-09 10:30:48

标签: plsql sqlplus

我正在尝试学习PL / SQL。我很震惊这个代码。请通知我哪里出错了。我在命令行中使用Oracle 10g。

declare
grade char(1):='&v_grade';
app varchar(15);
begin
app:=case v_grade
when 'a' then
dbms_output.put_line('Excellent');
when 'b' then
dbms_output.put_line('Good');
else
dbms_output.put_line('Bad');
end case;
dbms_output.put_line('Grade'||grade||' Appraisal:'||app);
end;
/

显示

Enter value for v_grade: a
old   2: grade char(1):='&v_grade';
new   2: grade char(1):='a';
dbms_output.put_line('Excellent');
                                 *
ERROR at line 7:
ORA-06550: line 7, column 34:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
. ( * % & = - + < / > at else end in is mod remainder not rem
when <an exponent (**)> <> or != or ~= >= <= <> and or like
LIKE2_ LIKE4_ LIKEC_ between || multiset member SUBMULTISET_
The symbol ";" was ignored.
ORA-06550: line 9, column 29:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
. ( * % & = - + < / > at else end in is mod remainder not rem
when <an exponent (**)> <> or != or ~= >= <= <> and or like
LIKE2_ LIKE4_ LIKEC_ between ||
ORA-06550: line 11, column 28:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
. ( * % & = - + < / > at end in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
LIKE4_ LIKEC_ between || multiset

请通知我我哪里出错了。

1 个答案:

答案 0 :(得分:3)

T.J。 Crowder是正确的,你不应该在SQL的case语句中有分号,但这是PL / SQL版本所以它略有不同。

您目前正在尝试将dbms_output.put_line过程(非功能)调用的(不存在的)回复分配给您的app变量。

要使分配工作,您需要case来评估字符串,因此您只需使用文字文字;但是分配需要在每个分支中:

declare
  grade char(1):='&v_grade';
  app varchar(15);
begin
  case grade
    when 'a' then app:= 'Excellent';
    when 'b' then app:= 'Good';
    else app := 'Bad';
  end case;

  dbms_output.put_line('Grade '||grade||' Appraisal: '||app);
end;
/

运行时获取:

Enter value for v_grade: a
Grade b Appraisal: Excellent

PL/SQL procedure successfully completed.

或使用查询来执行分配,尽管效率不高:

declare
  grade char(1):='&v_grade';
  app varchar(15);
begin
  select case grade
    when 'a' then 'Excellent'
    when 'b' then 'Good'
    else 'Bad'
  end case
  into app
  from dual;
  dbms_output.put_line('Grade '||grade||' Appraisal: '||app);
end;
/

Enter value for v_grade: b
Grade b Appraisal: Good

PL/SQL procedure successfully completed.

或者您可以直接在每个分支中执行输出:

declare
  grade char(1):='&v_grade';
begin
  dbms_output.put('Grade '||grade||' Appraisal: ');
  case grade
    when 'a' then
      dbms_output.put_line('Excellent');
    when 'b' then
      dbms_output.put_line('Good');
    else
       dbms_output.put_line('Bad');
  end case;
end;
/

Enter value for v_grade: c
Grade c Appraisal: Bad

PL/SQL procedure successfully completed.

输出的第一部分现在在案例之前。

你基本上混淆了不同的方法。

您可能希望将第一行更改为:

  grade char(1):= upper('&v_grade');

...然后让案例查找A,B,C而不是a,b,c - 那么输入在什么情况下无关紧要。

您可以阅读有关PL / SQL case statemnt herehere的更多信息。