使用if语句Oracle SQL Developer定义变量



我需要根据截至2月的财政年度调整日期范围

因此,当运行2020年1月的报告时,它需要计算从2017/12年(2018年2月(到2019/11年(20年1月(的24个月窗口。如何获得以下动态计算?

define v_report_month = 1
define v_report_year = 2020
define v_start_year = if &v_report_month > 1 then &v_report_year - 2  else &v_report_year - 3 end if
define v_start_monthno = if &v_report_month > 1 then &v_report_month - 1  else &v_report_month + 11 end if 
define v_end_year = if v_report_monthno > 2 then v_report_year else v_report_year - 1 end if
define v_end_monthno = if v_report_monthno > 2 then v_report_month - 2 else v_report_monthno + 10 end if

当我尝试运行以下内容时,只需获得--"ORA-00933:SQL命令未正确结束">

select
&v_start_year as y
,&v_start_monthno as m
from dual;

您可以使用PL/SQL匿名块,这会更简单:

SET SERVEROUTPUT ON
DECLARE
v_report_month   NUMBER := 1;
v_report_year    NUMBER := 2020;
v_start_year     NUMBER;
BEGIN
v_start_year :=
CASE
WHEN v_report_month > 1 THEN
v_report_year - 2
ELSE v_report_year - 3
END;
dbms_output.put_line('Start year: '||v_start_year);
END;
/
Start year: 2017

PL/SQL procedure successfully completed.

相同的CASE表达式可以使用IF-THEN-ELSE:编写

IF v_report_month > 1 THEN
v_start_year := v_report_year - 2;
ELSE
v_start_year := v_report_year - 3;
END IF;

如果你想保留你在SQL*Plus中定义的变量,那么你可以这样做:

define v_report_month = 1
define v_report_year = 2020
set serveroutput on
DECLARE
v_report_year   NUMBER;
v_start_year    NUMBER;
BEGIN
v_start_year :=
CASE
WHEN &v_report_month > 1 THEN
&v_report_year - 2
ELSE &v_report_year - 3
END;
dbms_output.put_line(v_start_year);
END;
2017

PL/SQL procedure successfully completed.

最新更新