简体   繁体   中英

Defining a variable using an if statement Oracle SQL Developer

I need to adapt a date range based on financial year ending in Feb.

So when the Jan-2020 report is run, it needs to calculate the 24 month window to start from 2017/12 (Feb-2018) to 2019/11 (Jan-2020). How do I get the below to calculate dynamically?

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

When I try running the following below, just get -- "ORA-00933: SQL command not properly ended"

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

You could use PL/SQL anonymous block which would be simpler:

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.

The same CASE expression could be written using 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;

If you want to leave the variables which you have defined in SQL*Plus, then you could do it this way:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM