In the SQL Server, I can define local variables like this.
declare @id number := 1000
select * from tbl_A where id = @id;
select * from tbl_B where id = @id;
It is very convenient.
I tried to do same thing in PL/SQL
but it doesn't work.
DECLARE id number;
select 1000 into id from dual;
Do you know how to do something similar? The simplest method is my objective.
Local Variable: Local variables are the inner block variables which are not accessible to outer blocks. Global Variable: Global variables are declared in outermost block.
It has to be in the execution and/or exception blocks: CREATE PROCEDURE proc ( param1; -- don't forget the data type here! , param2; -- or here! ) AS variable1 INT; BEGIN SELECT MAX(value) INTO variable1 FROM table WHERE field = param1; ... Save this answer.
To assign a default value to a variable, you use the assignment operator ( := ) or the DEFAULT keyword. In this example, instead of using the assignment operator := , we used the DEFAULT keyword to initialize a variable.
Variable Declaration in PL/SQLPL/SQL variables must be declared in the declaration section or in a package as a global variable. When you declare a variable, PL/SQL allocates memory for the variable's value and the storage location is identified by the variable name.
If you want to define a local variable in PL/SQL, you need a complete PL/SQL block
DECLARE
id NUMBER;
BEGIN
SELECT 1000
INTO id
FROM dual;
END;
or just
DECLARE
id NUMBER := 1000;
BEGIN
<<do something that uses the local variable>>
END;
If you want to declare a variable in SQL*Plus
SQL> variable id number
SQL> begin
select 1000 into :id from dual;
end;
/
SQL> print id
ID
----------
1000
SQL> SELECT * FROM tbl_a WHERE id = :id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With