简体   繁体   English

Oracle PL/SQL:基于 oracle 中 sysdate 的日期返回日期

[英]Oracle PL/SQL : Return date based on the day for sysdate in oracle

I have a requirement where i have to pick data from DB based on start_date and end_date passed to it.我有一个要求,我必须根据传递给它的 start_date 和 end_date 从数据库中选择数据。

  • If sysdate is sunday then function should return start_date as date on saturday in YYYYMMDD format and end_date as date on saturday in YYYYMMDD format.如果 sysdate 是星期天,那么 function 应该返回 start_date 作为 YYYYMMDD 格式的星期六日期和 end_date 作为 YYYYMMDD 格式的星期六日期。
  • If sysdate is monday then start_date should be date on saturday and end_date should be of sunday.如果 sysdate 是星期一,那么 start_date 应该是星期六的日期,end_date 应该是星期日的日期。
  • If sysdate is tuesday then start_date should be date on saturday and end_date will be of monday..and so on..如果 sysdate 是星期二,那么 start_date 应该是星期六的日期,而 end_date 应该是星期一的..等等..

How will a function look like to return two dates in YYYYMMDD format based on req. function 如何根据 req.

It appears that start date is always Saturday, while end date is a day previous to sysdate .似乎开始日期始终是星期六,而结束日期是sysdate 的前一天

If that's so, here's how:如果是这样,方法如下:

My database speaks Croatian so I'm switching to English (and setting default date format, just to show what sysdate is);我的数据库说克罗地亚语,所以我切换到英语(并设置默认日期格式,只是为了显示sysdate是什么); you don't have to do that.你不必那样做。

SQL> alter session set nls_date_language = 'english';

Session altered.

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

Session altered.

The TEMP CTE mimics sysdate change. TEMP CTE模拟sysdate 更改。 next_day function searches for Saturday previous to sysdate . next_day function 搜索sysdate之前的星期六。

21.11.2021 is Sunday, so you want to get 20.11.2021 as start and end dates: 21.11.2021 是星期日,因此您希望获得 20.11.2021 作为开始和结束日期:

SQL> with temp as (select date '2021-11-21' sys_date from dual)
  2  select
  3    sys_date,
  4    to_char(next_day(sys_date, 'SATURDAY') - 7, 'yyyymmdd') as start_date,
  5    to_char(sys_date - 1, 'yyyymmdd') as end_date
  6  from temp;

SYS_DATE   START_DA END_DATE
---------- -------- --------
21.11.2021 20211120 20211120

23.11.2021 is Tuesday, so you want to get Saturday as start date and Monday as end date: 23.11.2021 是星期二,因此您希望将星期六作为开始日期,将星期一作为结束日期:

SQL> with temp as (select date '2021-11-23' sys_date from dual)
  2  select
  3    sys_date,
  4    to_char(next_day(sys_date, 'SATURDAY') - 7, 'yyyymmdd') as start_date,
  5    to_char(sys_date - 1, 'yyyymmdd') as end_date
  6  from temp;

SYS_DATE   START_DA END_DATE
---------- -------- --------
23.11.2021 20211120 20211122

SQL>

In reality, you'd just实际上,你只是

SQL> select
  2    sysdate,
  3    to_char(next_day(sysdate, 'SATURDAY') - 7, 'yyyymmdd') as start_date,
  4    to_char(sysdate - 1, 'yyyymmdd') as end_date
  5  from dual;

SYSDATE    START_DA END_DATE
---------- -------- --------
18.11.2021 20211113 20211117

SQL>

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

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