I just started learning PL/SQL, I know I can use nested blocks to declare variable inside the execution section but can I do it without a nested block?
For example:
Begin
Var x number;
End;
Tried using var keyword, it didn't work.
I just started learning PL/SQL, I know I can use nested blocks to declare variable inside the execution section but can I do it without a nested block?
For example:
Begin
Var x number;
End;
Tried using var keyword, it didn't work.
Use the DECLARE
section of the PL/SQL block to declare variables:
DECLARE
x NUMBER;
BEGIN
NULL; -- use x for something
END;
/
var
you tried is related to SQL*Plus, Oracle's command-line tool.
Can you use it? Sure:
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>
[EDIT], based on your comment: if you want to declare variable in executable section of a PL/SQL block, you can't do that the way you wanted:
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.
Variables are to be declared in DECLARE
section (that's what syntax says):
SQL> declare
2 l_var number;
3 begin
4 l_var := 5;
5 end;
6 /
PL/SQL procedure successfully completed.
However, you can embed a new PL/SQL block into existing executable section - just follow the rules (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>
Or, you can create a package that holds variables, constants, etc.
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>