Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to define a local variable in Oracle?

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.

like image 727
user595234 Avatar asked Jul 02 '12 17:07

user595234


People also ask

What is local variable in Oracle?

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.

How do I create a local variable in Oracle stored procedure?

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.

How do you set a variable in Oracle?

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.

How do you create a local variable in PL SQL?

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.


1 Answers

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
like image 104
Justin Cave Avatar answered Sep 24 '22 15:09

Justin Cave