oracle 我可以在PL/SQL中的执行块中声明变量吗?

iszxjhcz  于 2023-06-22  发布在  Oracle
关注(0)|答案(2)|浏览(144)

我刚开始学习PL/SQL,我知道我可以使用嵌套块在执行部分中声明变量,但我可以不使用嵌套块吗?
例如:

Begin
    Var x number;
End;

尝试使用var关键字,它不起作用。

isr3a4wc

isr3a4wc1#

使用PL/SQL块的DECLARE部分声明变量:

DECLARE
  x NUMBER;
BEGIN
  NULL; -- use x for something
END;
/
gblwokeq

gblwokeq2#

您尝试的var与Oracle的命令行工具SQL*Plus有关。
你会用吗当然可以:

SQL> var x number            --> declare it at SQL level
SQL> exec :x := 5            --> set its value

PL/SQL procedure successfully completed.

SQL> set serveroutput on
SQL> begin
  2    dbms_output.put_line(:x * :x);    --> use it in PL/SQL
  3  end;
  4  /
25                                       --> result

PL/SQL procedure successfully completed.

SQL>

[编辑],基于您的评论:如果你想在PL/SQL块的executable部分声明变量,你不能按照你想要的方式来做:

SQL> begin
  2    l_var number;
  3  end;
  4  /
  l_var number;
        *
ERROR at line 2:
ORA-06550: line 2, column 9:
PLS-00103: Encountered the symbol "NUMBER" when expecting one of the following:
:= . ( @ % ;
The symbol ":=" was substituted for "NUMBER" to continue.

变量将在DECLARE节中声明(这是语法的说法):

SQL> declare
  2    l_var number;
  3  begin
  4    l_var := 5;
  5  end;
  6  /

PL/SQL procedure successfully completed.

但是,您可以 * 嵌入 * 一个新的PL/SQL块到现有的可执行部分-只需遵循规则(DECLARE!):

SQL> begin
  2    declare               --> new PL/SQL block begins here ...
  3      l_var number;
  4    begin
  5      l_var := 5;
  6    end;                  --> ... and ends here
  7  end;
  8  /

PL/SQL procedure successfully completed.

SQL>

或者,您可以创建一个包含变量、常量等的包。

SQL> create or replace package pkg_var as
  2    l_var                 number;
  3    c_name     constant   varchar2(20) := 'Littlefoot';
  4  end;
  5  /

Package created.

SQL>

相关问题