简体   繁体   English

Oracle SQL 将 sql 值设置为变量

[英]Oracle SQL set sql values to variable

I am trying to compare dates between the same table.我正在尝试比较同一张表之间的日期。 I wanted to store each value to a variable and compare the if there is a month difference between the two dates.我想将每个值存储到一个变量中并比较两个日期之间是否有一个月的差异。

Here is my table structure:这是我的表结构:

TABLE NAME: SYSTEMPARAM表名:系统参数
SEQNO - INT primary key SEQNO - INT 主键
SYSTEMDATE - DATE系统日期 - 日期

Here is what I want to achieve:这是我想要实现的目标:

var startdate = "SELECT SYSTEMDATE FROM SYSTEMPARAM WHERE SEQNO = '1'";
var enddate = "SELECT SYSTEMDATE FROM SYSTEMPARAM WHERE SEQNO = '2'";

if(MONTHS_BETWEEN(startdate , enddate ){

  //Conditions here
}

I want to compare if there is a month difference between two sql statement.我想比较两个 sql 语句之间是否有一个月的差异。

"Procedural" means PL/SQL. “过程”是指 PL/SQL。 So, do it that way.所以,就那样做吧。

Just to know what dates represent:只是想知道日期代表什么:

SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

Table contents:表格内容:

SQL> select * From systemparam;

     SEQNO SYSTEMDATE
---------- ----------
         1 04.04.2021
         2 05.04.2021

Anonymous PL/SQL block:匿名 PL/SQL 块:

SQL> set serveroutput on
SQL> declare
  2    l_startdate systemparam.systemdate%type;
  3    l_enddate   systemparam.systemdate%type;
  4  begin
  5    select s.systemdate
  6      into l_startdate
  7      from systemparam s
  8      where s.seqno = 1;
  9
 10    select s.systemdate
 11      into l_enddate
 12      from systemparam s
 13      where s.seqno = 2;
 14
 15    if months_between(l_enddate, l_startdate) > 0 then
 16       dbms_output.put_line('Dates are not equal');
 17    end if;
 18  end;
 19  /
Dates are not equal

PL/SQL procedure successfully completed.

SQL>

Though, if there are any "months" between these two dates ("0.01" months between is still "months between", although tiny ), then they aren't equal so it is maybe more obvious to use if l_enddate <> l_startdate then instead, isn't it?但是,如果这两个日期之间有任何“月”(“0.01”月之间仍然是“月之间”,尽管很小),那么它们不相等,因此使用if l_enddate <> l_startdate then可能更明显相反,不是吗? Also, check another option of the SELECT statement:另外,检查SELECT语句的另一个选项:

SQL> declare
  2    l_startdate systemparam.systemdate%type;
  3    l_enddate   systemparam.systemdate%type;
  4  begin
  5    select max(case when s.seqno = 1 then s.systemdate end),
  6           max(case when s.seqno = 2 then s.systemdate end)
  7      into l_startdate,
  8           l_enddate
  9    from systemparam s;
 10
 11    if l_enddate <> l_startdate then
 12       dbms_output.put_line('Dates are not equal');
 13    end if;
 14  end;
 15  /
Dates are not equal

PL/SQL procedure successfully completed.

SQL>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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