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

Why this PL/SQL doesn't work?

我正在努力学习 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

请告诉我哪里出错了。

T.J。 Crowder 说得有点对,在 SQL 的 case 语句中不应该有分号,但这是 PL/SQL 版本,所以略有不同。

您当前正在尝试将 dbms_output.put_line 过程(非函数)调用中的(不存在的)return 分配给您的 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');

...然后让 case 查找 A、B、C 而不是 a、b、c - 那么输入的 case 是什么都无关紧要。

您可以阅读有关 PL/SQL case 声明的更多信息 here and here