sql - 使用 if 语句定义变量 Oracle SQL Developer
问题描述
我需要根据截至 2 月的财政年度调整日期范围。
因此,运行 2020 年 1 月报告时,需要计算从 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.
推荐阅读
- java - 我想使用片段登录,但 Stringrequest 有问题
- reactjs - 组件内多个测试的正确模拟功能
- python-3.x - 如何将来自 Matplotlib 图形的 png 存储在变量中?
- arrays - .NET 上的 Discord 机器人,对特定单词做出反应
- java - 构建querydsl时来自HqlSqlWalker的NullPointerException
- git - scm 触发构建上的 Jenkins git 分支选择
- android - 如何比较从 Google MLKit for Android 获取的两个 Face 对象
- java - Hibernate 双向 @OneToMany 映射返回列 'xxx' 不能为空
- qt - QEventLoop::wakeUp() 的目的是什么?
- javascript - BorderBottom 在视图顶部添加了 React Native