【问题标题】:Defining a variable using an if statement Oracle SQL Developer使用 if 语句定义变量 Oracle SQL Developer
【发布时间】:2020-02-17 08:21:06
【问题描述】:

我需要根据截至 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;

【问题讨论】:

    标签: sql oracle if-statement variables oracle-sqldeveloper


    【解决方案1】:

    您可以使用更简单的 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.
    

    【讨论】:

    • 如何在查询中调用这些变量值?当我使用通常的“&”措辞时,该值似乎不会持续存在:``` select &v_start_year as y from dual; ``` 即使我移动 END 块以包含此语句。
    • &SQL*Plus 替换变量,它在语句中作为替换变量名称的前缀。 SQL*Plus 预处理语句并替换变量的值。如果您有一个复杂的脚本或逻辑,那么在 SQL*Plus 中执行所有这些操作可能会很棘手。由于您使用的是条件语句,我更喜欢 PL/SQL。
    • 如果您想同时结合 SQL*Plus 和 PL/SQL,请参阅我的更新。
    • 感谢您提供的附加示例,但我仍在努力解决的问题是让 PL/SQL 定义的变量在代码块之外使用?此逻辑只是作为较大部分中的第一部分,其中更新开始和结束日期变量以表示后续查询中的不同时间过滤器。
    • 有很多方法可以让变量进出 PL/SQL。最好的方法是将代码放在一个过程中并使用 IN/OUT 参数。
    猜你喜欢
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多