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

前端 未结 5 1006
我在风中等你
我在风中等你 2021-01-05 07:43

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         


        
5条回答
  •  心在旅途
    2021-01-05 08:06

    General syntax to declare variable in PL/SQL is

    var_nm datatype [NOT NULL := var_value ];

    • var_nn is the name of the variable.
    • datatype is a valid PL/SQL datatype.
    • NOT NULL is an optional specification on the variable which this variable cannot be assigned null value.
    • var_value or DEFAULT value is also an optional specification, where you can initialize a variable with some specific value.
    • Each variable declaration is a separate statement and must be terminated by a semicolon.

    We can assign value to variables in one of the following two ways -

    1. direct assignment (Eg. var_nm:= var_value;)
    2. Using select from (Eg. SELECT col_nm INTO var_nm FROM tbl_nm [WHERE clause];)

    In you case as Justin Cave has already mentioned it can be

    DECLARE 
     id number; 
    BEGIN
     SELECT 1000 into id from dual;
     dbms_output.put_line('id : '|| id ); 
    END; 
    /
    

    OR

    DECLARE 
     id number := 1000; 
    BEGIN
     dbms_output.put_line('id : '|| id ); 
    END; 
    /
    

    NOTE: '/' i.e Back slash after END keyword indicates to execute the above PL/SQL Block.

提交回复
热议问题