在 Oracle 中定义局部变量的最简单方法是什么?

2021-12-24 00:00:00 variables oracle plsql

在 SQL Server 中,我可以像这样定义局部变量.

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;

非常方便.我试图在 PL/SQL 中做同样的事情,但它不起作用.

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.

推荐答案

PL/SQL中如果要定义局部变量,需要一个完整的PL/SQL块

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;

或者只是

DECLARE
  id NUMBER := 1000;
BEGIN
  <<do something that uses the local variable>>
END;

如果你想在 SQL*Plus 中声明一个变量

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

相关文章