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

前端 未结 5 1036
我在风中等你
我在风中等你 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 07:44

    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)
    

提交回复
热议问题