如何在 Oracle 中声明和使用变量?

Mar*_*son 20 oracle syntax oracle-10g

我的主要技能是使用 SQL Server,但有人要求我对 Oracle 查询进行一些调整。我编写了以下 SQL:

declare @startDate int
select @startDate = 20110501
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:

declare @startDate int
select @startDate = 20110501
Error at line 1
ORA-06550: line 1, column 9:
PLS-00103: Encountered the symbol "@" when expecting one of the following:

   begin function package pragma procedure subtype type use
   <an identifier> <a double-quoted delimited-identifier> form
   current cursor
Run Code Online (Sandbox Code Playgroud)

如何在 Oracle 中声明和使用变量?

ik_*_*elf 20

在 pl/sql 块中:

declare
 startdate number;
begin
  select 20110501 into startdate from dual;
end;
/
Run Code Online (Sandbox Code Playgroud)

使用绑定变量:

var startdate number;
begin
  select 20110501 into :startdate from dual;
end;
/
Run Code Online (Sandbox Code Playgroud)

PL/SQL 过程成功完成。

SQL> print startdate

 STARTDATE
----------
  20110501
Run Code Online (Sandbox Code Playgroud)

在查询中:

select object_name 
from user_objects 
where created > to_date (:startdate,'yyyymmdd');  /*prefix the bind variable wïth ":" */
Run Code Online (Sandbox Code Playgroud)


Jon*_*des 5

SQL*Plus 支持附加格式:

DEFINE StartDate = TO_DATE('2016-06-21');
DEFINE EndDate   = TO_DATE('2016-06-30');

SELECT
    *
FROM
    MyTable
WHERE
    DateField BETWEEN &StartDate and &EndDate;
Run Code Online (Sandbox Code Playgroud)

请注意要在查询中执行替换的 & 符号。