Number of days traversed in a stored procedure

Source: Internet
Author: User
Tags table name

Long time no write, today wrote a traversal of the number of days stored procedures, put out to share.

Declare
SqlString VARCHAR2 (32767);
Tempdate number (8,0);
Lnm_datefrom number (8,0); --Start time
Lnm_dateto number (8,0); --End time

Begin
lnm_datefrom:=20070305;
lnm_dateto:=20070308;

SqlString: = ' SELECT
Aa. Yearmonth as Getdatadate, BB. Dayaveragevalue
From
(
';

Tempdate: = Floor (Lnm_datefrom);
while (Tempdate<=floor (Lnm_dateto))
LOOP
SqlString: = SqlString | | ' SELECT ' | | Tempdate | | ' As Yearmonth from DUAL ';
IF (tempdate <> Floor (lnm_dateto)) Then
SqlString: = SqlString | | ' UNION All ' | | Chr (10);
END IF;
if (to_date (tempdate) = Last_day (To_date (tempdate))) Then
SELECT To_number (To_char (Add_months (To_date (tempdate), 1), ' yyyymm ')) | | Tempdate ' into ' from dual;

Else
Tempdate: =tempdate+1;
END IF;
END LOOP;

SqlString: = SqlString | |
'
) AA,
(
SELECT
A. Time field as Getdatadate
, A. Field 2 as Dayaveragevalue
, A. Field 3 as Daymaxvalue
, A. Field 4 as Dayminvalue
From
Aire. Table name A
WHERE
A. Time field between ' | | Lnm_datefrom | | ' and ' | | Lnm_dateto | | '
and A. Field cd = ' | | 1314| | '
and a.cd = ' | | 121| | '

) BB
WHERE
Aa. Yearmonth = BB. Getdatadate (+)
ORDER by AA. Yearmonth
' ;

Dbms_output.put_line (SqlString);

End

In fact, the cycle of time is very simple, the key is the following two sentences

if (to_date (tempdate) = Last_day (To_date (tempdate))) then--judgment is not the last day of one months
SELECT To_number (To_char (Add_months (To_date (tempdate), 1), ' yyyymm ')) | |  Tempdate ' into ' from dual; --generation of 1st next month

Else
Tempdate: =tempdate+1; --date increased by 1 days
END IF;

has been tested for adoption.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.