[英]Defining a variable using an if statement Oracle SQL Developer
我需要根據 2 月結束的財政年度調整日期范圍。
因此,當運行 Jan-2020 報表時,需要計算從 2017/12(2018 年 2 月)到 2019/11(2020 年 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.
可以使用IF-THEN-ELSE編寫相同的CASE表達式:
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.