Oracle
如何在 Oracle 中聲明和使用變數?
我的主要技能是使用 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 中聲明和使用變數?
在 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 ":" */
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;
請注意要在查詢中執行替換的與號。