26

My main skills are with SQL Server, but I have been asked to do some tuning of an Oracle query. I have written the following SQL:

declare @startDate int
select @startDate = 20110501

And I get this error:

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

How do I declare and use variables in Oracle?

Nick Chammas
  • 14,810
  • 17
  • 76
  • 124
Mark Allison
  • 525
  • 1
  • 4
  • 9

3 Answers3

23

Inside pl/sql block:

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

using a bind variable:

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

PL/SQL procedure successfully completed.

SQL> print startdate

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

in a query:

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

SQL*Plus supports an additional format:

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

SELECT
    *
FROM
    MyTable
WHERE
    DateField BETWEEN &StartDate and &EndDate;

Note the ampersands where the substitutions are to be performed within the query.

Jon of All Trades
  • 5,987
  • 7
  • 48
  • 63
1

In ORACLE SQL Developer 20.2.0.175, we can Run Script (F5):

DEFINE usr = 'YourName'; 
SELECT * FROM Department WHERE created_by = '&usr';
Ortsbo
  • 11
  • 1