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

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


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 numberSQL> begin       select 1000 into :id from dual;     end;     /SQL> print id        ID----------      1000SQL> SELECT * FROM tbl_a WHERE id = :id


Solution for Oracle SQL

DEF x = fooSELECT '&x' FROM dual;

The result will be : foo

NB: The variable will keep the value even after execution. To clear variable run UNDEFINE x.


An alternative to DECLARE Block is to use a WITH Clause:

WITH my_params AS (    SELECT 123 AS min_id FROM DUAL) SELECT * FROM some_table WHERE id > (SELECT min_id FROM my_params)

It is more portable as many vendors support the WITH clause and you can change seamless from parameter to dynamic value. For example:

WITH my_params AS (    SELECT min(id) AS min_id FROM some_id_table) SELECT * FROM some_table WHERE id > (SELECT min_id FROM my_params)