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


18

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

declare @startDate int
select @startDate = 20110501

我得到这个错误:

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

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

Answers:


18

在pl / sql块内部:

declare
 startdate number;
begin
  select 20110501 into startdate from dual;
end;
/

使用绑定变量:

var startdate number;
begin
  select 20110501 into :startdate from dual;
end;
/

PL / SQL过程成功完成。

SQL> print startdate

 STARTDATE
----------
  20110501

在查询中:

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

不幸的是,这对我不起作用。var my_num NUMBER; 从double开始选择12345到my_num中;结束; /从my_table sa中选择*,其中sa.my_col =:my_num;
马修

你得到什么错误?(经过测试并可以正常工作)
ik_zelf

我实际上尝试了Jon of All Trades发布的解决方案,该解决方案非常适合我的需求-即使用DEFINE并使用&引用变量。
马修

3

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;

请注意在查询中要在其中执行替换的与号。


使用任何的这些功能时,这为我工作在蟾蜍为Oracle:Execute as scriptExecute via Toad script runnerExecute via SQL*Plus。但是,如果尝试使用运行,Execute/compile statement at caret它将返回错误消息:“ ORA-009000:无效的SQL语句”。
SherlockSpreadsheets
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.